Google News
logo
How to Create Object in Java with Example Program?
To create an object in Java, you need to follow these steps :

Define a class : A class is a blueprint or template for creating objects. It defines the data and behavior of the objects.

Instantiate the class : To create an object, you need to create an instance of the class using the "new" keyword.

Call the constructor : When you create an instance of the class, the constructor is called to initialize the object.

Here is an example program that demonstrates how to create an object in Java :
Program :
public class Student {
    String name;
    int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void display() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 20);
        Student s2 = new Student("Jane", 22);
        
        s1.display();
        s2.display();
    }
}


In this example, we have defined a class called "Student" that has two instance variables - "name" and "age" - and a constructor that takes two parameters to initialize these variables.

In the main method, we have created two instances of the Student class - s1 and s2 - by calling the constructor and passing in the name and age values. We have then called the "display" method on each object to print out their values.

Output :
Name: John
Age: 20
Name: Jane
Age: 22
This demonstrates how to create objects in Java using a class and constructor.