user1635256
user1635256

Reputation: 111

toString : when does it return ClassName@HexValue, String Value associated with it

As per definition toString() returns "Returns a string representation of the object as:

getClass().getName() + '@' + Integer.toHexString(hashCode())

But sometimes I could see even if it is not Overriden in our class, it returns the String associated with it. I mean Object.toString() returns some String but not "ClassName@HexCode".

When does this happen. Please let me know whats the reason behind this ??

Upvotes: 0

Views: 1330

Answers (2)

Deepak Ingole
Deepak Ingole

Reputation: 15752

The default behavior of toString() is to return the object as

getClass().getName() + '@' + Integer.toHexString(hashCode()).

But if you override toString() in base class or child class you can specify the way your object should be printed.

Probably in your case its using the inherited method of your base class .

Ex:

class Person {
    private String myName; // name of the person
    private int myAge; // person's age
    private String myGender; // 'M' for male, 'F' for female

    // constructor
    public Person(String name, int age, String gender) {
        myName = name;
        myAge = age;
        myGender = gender;
    }

    public String getName() {
        return myName;
    }

    public int getAge() {
        return myAge;
    }

    public String getGender() {
        return myGender;
    }

    public void setName(String name) {
        myName = name;
    }

    public void setAge(int age) {
        myAge = age;
    }

    public void setGender(String gender) {
        myGender = gender;
    }

    public String toString() {
        return myName + ", age: " + myAge + ", gender: " + myGender;
    }
 }
 public class Teacher extends Person {
 //...
 }

 calling `toString();` method will call inherited `tOString()` method of base class and will return `return myName + ", age: " + myAge + ", gender: " + myGender;`

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136062

It's only possible if a class extends another class with overriden (or inherited overriden) toString().

Upvotes: 4

Related Questions