Java is an Object-Oriented Programming Language, so everything in java is related to class and its objects. It is known as the instance of the class. An object can also be called a physical existence of the logical template class. The object is a real-world and runtime entity.
In the real world, we can understand an object like a laptop with its properties like name, cost, color, etc., and behavior like sending emails, writing the code, etc.
An object is something that has a state and behavior. The object is called the instance or blueprint of the class.
State: Represents the data.
Behavior: Represents the functions of an object.
Identity: JVM identifies each object uniquely, so objects’ names must be different if we are creating more than one object for the same class.
className NameOfObject = new className();
Employee emp = new Employee()
Here, emp is the object that represents class Employee during runtime.
There are three ways through which we can initialize the object in Java:-
It means the object itself stores the data.
ClassName obj1 = new ClassName();
obj1.var1PresentInClassName = 10;
obj1.var2PresentInClassName = “Jonny”;
Note: We can create as many objects for a single class to store the various information.
In constructor initialization, the objects are initialized by the constructor.
class Vehicle {
int number;
public Vehicle(int number) {
this.number = number;
}
}
Or
ClassName objectName = new ClassName(number);
In method initialization, we create a variable as a parameter for the method and assign them inside the method.
class Fruit{
int number;
String type;
void Price(int n, String t){
number = n;
type = t;
}
}
Let’s create an object for the above class Employee
Employee emp= new Employee();
Here, emp is the object that represents class Employee during runtime.
Knowledge2life
Knowledge2life
Knowledge2life
|