Create class Objects in Java using new operator

Java 8Object Oriented ProgrammingProgramming

Class objects can be created in Java by using the new operator. A class is instantiated by the new operator by allocating memory for the object dynamically and then returning a reference for that memory. A variable is used to store the memory reference.

A program that demonstrates this is given as follows:

Example

 Live Demo

class Student {
   int rno;
   String name;
   public Student(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(15, "Peter Smith");
      s.display();
   }
}

Output

Roll Number: 15
Name: Peter Smith

Now let us understand the above program.

The Student class is created with data members rno, name. A constructor initializes rno, name and the method display() prints their values. A code snippet which demonstrates this is as follows:

class Student {
   int rno;
   String name;
   public Student(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 by using the new operator. 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(15, "Peter Smith");
      s.display();
   }
}
raja
Published on 15-Feb-2019 06:56:12
Advertisements