Tuesday, 17 March 2015

Q. What is class, object and instance ?

Ans: Class: class is a blueprint or template which is used to create objects.For example- Suppose you have to make a car and so you made a protype or blueprint on paper that the car will have four wheels,one starring,two headlights etc...etc..Basically, a class will consists of fields,methods and constructors.Field is used to hold the state of the class. Method is used to represent the behavior of the class e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear). Constructor is used to create a new Instance of the Class.


Objects: Now, using that protype or blueprint you can make N number of cars which is nothing but objects.Any entity that has state and behavior is known as an object. An object stores its state in fields and exposes its behavior through methods e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear).


Instance: Nowwill that car created on paper run ...?.No, because it is on paper.An actual object in memory is called an instance.An instance is a unique copy of a class that represents an object. When a new instance of a class is created, the JVM will allocate memory for that class instance.The instance of the object is created using new operator.

      

         e.g   Car c=new Car();


No comments:

Post a Comment