How to create an Object in Java

463 views
optmiize_your_resume_1

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); } }
Code language: JavaScript (javascript)

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); } }
Code language: JavaScript (javascript)
20%off for Ink 280 281

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More