Thursday, June 22, 2017

Java-Classes and Objects

classes and objects
-------------------
object
------
An object is a real world entity like Car,Bus,Bike
It is an instance of a class i,e it allocates memory for a class.

An object has

i)properties
ii)actions


properties are used to identify object.
actions are behaviours

ex:

Car
Properties -->name
           -->color
           -->price
           -->cno

actions-->move()
       -->acceleration()
       -->speed()

Properties are represented using variables.

Actions are represented using methods.


syntax
------
ClassName referenceName=new ClassName();


class
-----
A class is blue print of an object

A class describes about properties and actions of an object.

A class is collection of variables and methods.

A class is declared by using a keyword "class".

syntax
------
accessmodifier class ClassName
{
  variables;
  methods;
}

ex:
Car-->name---String
   -->color--String
   -->price--double
   -->cno  --int


steps for working with classes and objects
------------------------------------------
step1:
 declare a class

 syntax
 ------
 accessmodifier class ClassName
 {
   //variables
   //methods
 }

 ex:
 class Car
 {
 
 }

step2
----
create an object for a class.

syntax
------
ClassName referenceName=new ClassName();

ex:
Car c=new Car();

Step3
-----
Accessing members of a class.

syntax
------
referenceName.memberName

How to access variable
----------------------
referenceName.varname

ex:
c.name

How to access a method
----------------------
referenceName.methodname();

ex:
c.input();


Program
-------
class Book
{
  String name="harrypotter";
  String author="jkrowling";
  double price=1000.00;
}
class BookTest
{
  public static void main(String args[])
  {
     Book b=new Book();
     System.out.println(b.name);
     System.out.println(b.author);
     System.out.println(b.price);
  }
}

In the above we are declaring 2 classes

i)Book
ii)BookTest


Book is used describes about book properties

BookTest is a test class where we include main method to it
and test Book i,e creating objects and accessing members of a class.

main() is the starting point of execution to jvm.


No comments: