Here are few points which we need to understand about classes and objects.
- A class is like a blue print and we can create as many objects using that class.
- All the objects of one class will have same properties and they will be copied from that class
- We can create multiple objects of a class and multiple objects can be of same class
- Every object should belong to a class, since we can not create objects with out a class
- A class is also referred as type and an object is also referred as instance.
To understand the difference between a class and objects, let us look at the following examples.
Compared to the creation of primitive types, creating an instance (or object) of
class (or type) is different. We have to use the
keyword for creating an object of non-primitive data type or user defined data type.
in primitive types, the moment a variable is declared, the space required for that variable is also allocated.
int a = 5;
This declares the variable
and allocates 4 bytes for that integer. But with classes (or non-primitive data types), the allocation of the space required for that object has to be done using
keyword as shown below.
If the class
is declared like this
we can create object for student Mahesh
Student mahesh = new Student();
Similarly, we can also create student objects like
as shown below.
Student ntr = new Student();
Student prabhas = new Student();
Student arjun = new Student();
Above, the right side of equals shows how to create objects and
are called references. We will discuss more about references in Java Objects References