Home Java Tutorial How to create an Object in Java

How to create an Object in Java

by anupmaurya
1 minutes read

The object is a basic building block of an OOPs language. In Java, we cannot execute any program without creating an object. There is various way to create an object in Java ,here we are going to know one of easy way to create an object using new keyword.

To create an object of MyClass, specify the class name, followed by the object name, and use the keyword new:

Example

Create an object called “myObj” and print the value of x:

public class Main {
  int x = 5;

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

Multiple Objects

You can create multiple objects of one class:

Example

Create two objects of Main:

public class Main {
  int x = 5;

  public static void main(String[] args) {
    Main myObj1 = new Main();  // Object 1
    Main myObj2 = new Main();  // Object 2
    System.out.println(myObj1.x);
    System.out.println(myObj2.x);
  }
}

You may also like

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.