Override the toString() method in a Java Class

Java 8Object Oriented ProgrammingProgramming

A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.

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 String toString() {
      return rno + " " + name;
   }
}
public class Demo {
   public static void main(String[] args) {
      Student s = new Student(101, "Susan Bones");
      System.out.println("The student details are:");
      System.out.println(s);
   }
}

Output

The student details are:
101 Susan Bones

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 overridden method toString() displays a string representation of object s. 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 String toString() {
      return rno + " " + name;
   }
}

In the main() method, an object s of class Student is created with values 101 and “Susan Bones”. Then the object s is printed. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      Student s = new Student(101, "Susan Bones");
      System.out.println("The student details are:");
      System.out.println(s);
   }
}
raja
Published on 19-Feb-2019 05:39:23
Advertisements