ADVERTISEMENTS

How to Create Object in Java

In Java, an object is an instance of a class. An object represents a specific instance of a class and contains its own set of data and methods. Objects are created using the new keyword followed by the constructor of the class.

The following example will explain you about example of creating an object of a class Person:

class Person {
  private String name;
  private int age;
  // constructor
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  // getters and setters
}

// create an object of the Person class
Person person1 = new Person("John Doe", 30);

 

In the above example, the 'Person' class has a constructor that takes two arguments: a name and an age. The 'new' keyword is used to create an instance of the class, and the constructor is called with the arguments "John Doe" and 30 to initialize the object's properties.

It's important to note that not all classes have public constructors and not all classes are designed to be instantiated. Some classes are designed to be used as a utility or a library, and objects of these classes are usually not created by the client code.

Java is used for developing mobile apps, web applications, games, and other software. It is known for its "write once, run anywhere" (WORA) principle, which means that Java code can be run on any device that has a Java Virtual Machine (JVM) installed. You can learn java from our Java Tutorials and Java Examples

ADVERTISEMENTS