A class acts as a blue-print that defines the properties, states, and behaviors
that are common to a number of objects. An object is an instance of the class.
For example, you have a class called Vehicle and Car is the object of that
class. You can create any number of objects for the class named Vehicle, such as
Van, Truck, and Auto.
The new operator is used to create an object of a class. When an object of a
class is instantiated, the system allocates memory for every data member that is
present in the class.
Difference between Class vs Object in OOPS and Java
Class and Object are related to each other because every Object must be type of
any class. In the same time class itself is of no use until you create object.
Let’s see these difference between class and object in points :
a) Class is blueprint means you can create different object based on one class
which varies in there property. e.g. if
Car is a class than Mercedes, BMW or Audi can be considered as object because
they are essentially a car but have different size, shape, color and feature.
b) A Class Java contains both state and behavior, state is represented by
field in class e.g. numberOfGears, whether car is automatic or manual, car is
running or stopped etc. On the other hand behavior is controlled by functions,
also known as methods in Java e.g. start() will change state of car from stopped
to started or running and stop() will do opposite.
c) Object is also called instance in Java and every instance has different
values of instance variables.
Generally, an object is an instance of a class. For example:
class sum //declaration of a class{ int a=50; //declaration of variables int b=60; int c; public void add()// defining a function {c=a+b; System.out.println("The sum is="+c); } public static void main(String args[])// main function { sum s= new sum();// making a object of class sum s.add(); //accessing the function with the help of object }} |
Another difference between Class and Object
in Java is that we have a class keyword to declare class in Java but there is no
object keyword. Objects are most notably created using new() operator, which
calls constructor of class to create and initialize object in Java.