Object


Object

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.

Syntax:

className NameOfObject = new className();

Example

Employee emp = new Employee()
Here, emp is the object that represents class Employee during runtime.

What are the ways to initialize the object?

There are three ways through which we can initialize the object in Java:-

  • By reference variable

      It means the object itself stores the data.

      Example:

      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.

  • By constructor

      In constructor initialization, the objects are initialized by the constructor.

      Example:

      class Vehicle {
           int number;
           public Vehicle(int number) {
            this.number = number;
         }
      }
      Or
      ClassName objectName = new ClassName(number);

  • By method

      In method initialization, we create a variable as a parameter for the method and assign them inside the method.

      Example:

      class Fruit{
           int number;
           String type;
           void Price(int n, String t){
           number = n;
           type = t;
         }
      }

Example:

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.


Example No.1:

Com.knowledge2life public class Main { String x= "Knowledge2life"; public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } }

OUTPUT:

Knowledge2life

Example No.2:

Com.knowledge2life public class Main { String x= "Knowledge2life"; public static void main(String[] args) { Main myObj1 = new Main(); Main myObj2 = new Main(); System.out.println(myObj1.x); System.out.println(myObj2.x); } }

OUTPUT:

Knowledge2life
Knowledge2life