Create Objects of a Class in Java

Java 8Object Oriented ProgrammingProgramming

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();
   }
}
raja
Published on 12-Feb-2019 10:11:48
Advertisements