Class with a constructor to initialize instance variables in Java

Java 8Object Oriented ProgrammingProgramming

A class contains a constructor to initialize instance variables in Java. This constructor is called when the class object is created.

A program that demonstrates this is given as follows −

Example

 Live Demo

class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public 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(173, "Susan");
      s.display();
   }
}

The output of the above program is as follows −

Roll Number: 173
Name: Susan

Now let us understand the above program.

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

class Student {
   private int rno;
   private String name;
   public Student(int r, String n) {
      rno = r;
      name = n;
   }
   public 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 with values 101 and “John”. Then 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(173, "Susan");
      s.display();
   }
}
raja
Published on 07-Feb-2019 11:07:33
Advertisements