How to Create Object in Java with Example

In this tutorial, we will learn how to create an object in Java with the help of examples.

We know that everything is an object in Java. A class is a model or user-defined blueprint for creating objects. It encapsulates the relevant data members and methods (behaviors) that an object of that class will have.

A simple example of a Java class is as:

public class Car {
 // Declaration of variables
    String make;
    String model;
    int year;

 // Declaration of methods
    void start() {
        System.out.println("Engine started.");
    }
    void stop() {
        System.out.println("Engine stopped.");
    }
}

In this example, we have created a class named “Car” that contains three instance variables (make, model, and year) and two instance methods (start() and stop()).

Creating an object means allocating memory to store the data of variables temporarily. That is, we create an object of a class to store data temporarily.

Creating an object is also called instantiating an object. By creating an object, we can access members of any class. So, let us understand how to create an object or instance of a class in Java?

How to Create Object of Class in Java?


In Java, we can create an object or an instance of a class using the new keyword in three steps. They are as follows.

  1. Declaration of a reference variable.
  2. Creation of an object.
  3. Linking the object and the reference variable.

Steps to create object in Java

Declaration of  Reference variable


Basically, the declaration of an object means refers to an object. A general form of declaration of a reference variable is as below.

Classname object_reference_variable; // Creating a reference variable of type Class.

The Classname is the name of the class which is being instantiated. The object reference variable is a variable of type Classname.


For example, consider a class whose name is College and object reference variable myCollege. We can declare it like this:

 College myCollege;

This statement tells the JVM to allocate memory space for a reference variable and names that reference variable myCollege. The reference variable is of type College.

Creating Object in Java


We can create an object in a general form like this:

new Classname(); // Creating an object of class.

The class name followed by parentheses represents the constructor of the class.
For example,

new College();

This statement tells the JVM to allocate memory space for a new College object on the heap.

Linking Object and Reference variable


Now, we will link the object and reference created above like this:

// This is a general syntax for creating an object of any class in Java.
  Classname object_reference_variable = new Classname();

Assigns the new College to the reference variable myCollege.

College myCollege = new College();

where,

College ➝ Name of the class.
myCollege ➝ Object reference variable which stores the address of the object in the stack memory.
new ➝ keyword that stores the object in the heap memory.
College() ➝ Constructor of the class.
= ➝ The equal sign (=) is an assignment operator. It simply says to take the object created by a new keyword and assign it to the object reference variable.

Hash Code Number


When an object of class is created, the memory is allocated in the heap area to store instance variables. After the creation of an object, JVM produces a unique reference number (address) for that object. This unique reference number is called hash code number.

This reference number is unique for all objects, except string objects. The address of the object is stored in the object reference variable in the stack memory.

We can know the hash code number or reference number (address) of an object by using hashCode() method of Object class.

The following code can be used to know the hash code number.

College myCollege = new College(); 
System.out.println(myCollege.hashCode()); // It will display hash code stored in myCollege.

Memory Allocation for Storing an Object in Java


Let’s understand the memory allocation for storing an object in Java by given below figure.

Memory allocation of object creation in Java

Explanation:

When the statement College myCollege = new College(); will be executed by JVM, an object will be created in the heap memory and stores the data “Hello Java” in it.

The address of the object is stored in the reference variable myCollege in the stack memory.

Remember that creating an object in Java means allocating memory for storing data. We can also create an object of the class in two steps like this:

Step 1: College myCollege; // Declaration of reference to the object.
Step 2: myCollege = new College(); // Creating an object.

How to Create Multiple Objects in Java


Java allows us to create multiple objects of a single class. Creating multiple objects of one type is as follows:

College myCollege1 = new College();
College myCollege2 = new College();

Both reference variables have different memory addresses.

Creating an object of a class with passing different parameters to the constructor is as:

Student st = new Student(); // It will call default constructor.
Student st = new Student("DEEP"); // It will call parametrized constructor.

Object Reference in Java


An object reference is a unique hexadecimal number that represents a memory address of the object. It is useful to access members of objects.

When a new object is created, a new reference number is allocated to it. It means that every object in Java will have a unique reference.

New Keyword in Java


In Java, a new operator is a special keyword which is used to create an object of the class. It allocates the memory to store an object during runtime and returns a reference to it.

This reference is the address of the object in the heap memory allocated by the new operator.

This reference (memory address) is then stored in a variable called object reference variable that can be accessed from anywhere in the application. See the image below.

For Which Purpose We Create Object of Class in Java


We create an object in Java applications because of three reasons. They are as follows:

1. Since Java is a purely object-oriented programming language. So Everything is done in the form of objects only. Therefore, objects are required in the Java programming language.

2. To store data temporarily in Java application, we require to create an object. The object provides temporary storage for our data.

3. In Java, By creating an object, we can call the members of one class from another class. It is useful when we need to use common code in every class again and again.

4. To access members of any particular class, we have to create an object of the respective class

Whenever we create an object in any program, the Object reference variable is automatically generated. By using this object reference variable only, we can access the members of a particular class.

The reference variable must have a reference value. The Dot(.) operator gives you to access an object’s state and behavior (instance variables and methods).  These are the reasons for which we create objects in Java programs.

How many Ways to Create Object in Java


There are several ways to create an object of class in Java. They are as follows.

  1. Using the new keyword
  2. Using Class.forName
  3. Using Clone.
  4. Using Object Deserialization.
  5. Using ClassLoader.

In this tutorial, we have discussed object creation using the new keyword. In the further tutorial, we will know about other ways to create an object of class.

Using new keyword is the most basic and common way to create an object of a class in Java. Almost 99% of objects are created using the new keyword.

We can call any constructor using this method, whether it is a non-argument or a parametrized constructor.

Object Creation in Java with Examples


Let’s take a very simple example program in which we will understand the concept of object creation step by step. Here, we will create a class “HelloJava” that will contain a method display() and we will create an object of class to access that method.

Example 1:

package scientecheasy;
// Step 1: Create a class named HelloJava. 
  public class HelloJava
  { 
// Step 2: Declare a default constructor.
   HelloJava()
   { 
 // This statement will print the message on the console. 
    System.out.println("Hello Java"); 
   } 
 // Step 3: Declare a method that will print a message which we want.
    void display()
    { 
       System.out.println("Welcome to online Java tutorial point. ");
    }
// Step 4: Declare the main method to start the execution of program. This method is static.
   public static void main(String[] args)
   { 
// Step 5: Create an object of the class with the object reference variable 'obj'.
   HelloJava obj = new HelloJava(); // It will call default constructor as object created.

// Step 6: Call the method using object reference variable 'obj' to print output on the console.
    obj.display();
   } 
 }
Output: 
      Hello Java 
      Welcome to online Java tutorial point.

Remember that when we write anything in class, it is applicable to all its objects. If we create a method in the class, it is available as it is to all of class objects.

For example, in the preceding program, a class HelloJava contains a method display() that prints a message on the console.

If we create three objects to this class, all three objects of this class get a copy of this method and from any object, we can call and use this method. Let’s understand it more clearly with another example program.


Let’s take an example program in which we create three objects of a class and access the same method using three objects.

Example 2: 

package objectProgram;
public class Hello
{ 
// Declaration of instance method.
   void display() 
   { 
      System.out.println("Hello Java");
   }
public static void main(String[] args)
{ 
// Create three objects of a class to access the same method. 
   Hello h1 = new Hello(); 
   Hello h2 = new Hello(); 
   Hello h3 = new Hello(); 

// Call instance method display() using reference variable h1, h2, and h3. 
   h1.display();
   h2.display(); 
   h3.display(); 
 } 
}
Output: 
      Hello Java 
      Hello Java 
      Hello Java

In the preceding example, we have created three objects of a class Hello and they are calling the same method display(). Here, the method is available to all class objects.

What is System.out.println()


1. System is a class that is pre-defined by the Sun Microsystem.

2. out is a variable declared in System class of type PrintStream.

3. println is a method defined in PrintStream class.

What is void in Java


Void is a keyword that indicates that this method does not provide or return any data back to the class of an object. Let’s take an example program in which we will calculate the sum of two numbers. You follow all the above steps.

Example 3:

package objectProgram;
public class Sum 
{ 
// Declare instance variables. 
   int a;
   int b;

// Declare a default constructor and initialize the value of variables. 
// You can also initialize directly to the variables. This is another way to initialize the value of variables. 
   Sum()
   { 
      a = 50;
      b = 20; 
   } 
// Declare a method and write the logic to add the numbers. 
   void display()
   {
     int sum = a + b; 
     System.out.println("Sum of two numbers: " +sum );
   } 
public static void main(String[] args) 
{ 
 // Create an object of the class and call the method using reference variable to print output on the console. 
    Sum sm = new Sum(); 
    sm.display(); 
   } 
  }
Output: 
       70

If you are a beginner and unable to understand this program, then you go for the next tutorial. You can easily understand after the next tutorial.  Hope that you will have understood how to create an object in Java. Keep in mind the following points for object creation in Java.


Key Points to Remember:

1. An object of class is created by calling constructor of the corresponding class through a new operator.

2. It is mainly created in three steps: Declaration, Instantiation, and Initialization.

3. In declaration, we simply define a variable with an object type.

4. Instantiating a class refers to creating an object of class that is done by using the new operator.

5. In initialization, we link new object with a reference variable.

6. Reference variable holds address of an object whereas a variable holds the data.

⇐ PrevNext ⇒

Please share your love