Create Objects of a Class in Java



An object is created from a class using three steps i.e. declaration, instantiation, initialization. First the object is declared with an object type and object name, then the object is created using the new keyword and finally, the constructor is called to initialize the object.

A program that demonstrates object creation is given as follows −

Example

 Live Demo

class Student {
   int rno;
   String name;
   void insert(int r, String n) {
      rno = r;
      name = n;
   }
   void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}
public class Demo {
   public static void main(String[] args) {
      Student s = new Student();
      s.insert(101, "John");
      s.display();
   }
}

The output of the above program is as follows −

Roll Number: 101
Name: John

Now let us understand the above program.

The Student class is created with data members rno, name and member functions insert() and display(). A code snippet which demonstrates this is as follows:

class Student {
   int rno;
   String name;
   void insert(int r, String n) {
      rno = r;
      name = n;
   }
   void display() {
      System.out.println("Roll Number: " + rno);
      System.out.println("Name: " + name);
   }
}

In the main() method, an object s of class Student is created. Then insert() method is called with parameters 101 and “John”. Finally the display() method is called. A code snippet which demonstrates this is as follows −

public class Demo {
   public static void main(String[] args) {
      Student s = new Student();
      s.insert(101, "John");
      s.display();
   }
}

Advertisements