
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Override the toString Method in a Java Class
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
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); } }
Advertisements