Академический Документы
Профессиональный Документы
Культура Документы
Let us take a Person class and try to print the person object using the System.out.println() statement.
package blog.javabynataraj; //@author Muralidhar N class Person{ public String fname; public String lname; Person(String fn,String ln){ this.fname=fn; this.lname=ln; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } } public class ToStringTest { public static void main(String[] args) { Person p = new Person("murali","dhar"); System.out.println(p); } }
But here we assumed that the firstname and the lastname will be print. But it is not done. This is the magic toStirng method. But in the below program we can print the firstname and lastname of person Object. What we are going to do here is just overriding the toString method in Person Class.
package blog.javabynataraj; //@author Muralidhar N class Person{ public String fname; public String lname; Person(String fn,String ln){ this.fname=fn; this.lname=ln; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String toString(){ return (getClass()+" FirstName: "+fname+" } } public class ToStringTest { public static void main(String[] args) { Person p = new Person("murali","dhar"); System.out.println(p); } }
LastName: "+lname);
See the output of this: Now you can achieve this by overriding the default toString() method inside Person class to return the contents of the instance of Person.