SantiagoM SantiagoM - 1 month ago 24
Java Question

Java inheritance why does this toString prints BB and not AB, AB?

I'm executing this and i cant understand why does this executes and prints BB in both lines.

class A {
public String toString(){
return this.getClass().getSimpleName();
}
}

class B extends A {

public String toString(){
return super.toString() + this.getClass().getSimpleName();
}
}

public class Main {
public static void main(String[] args) {

A a = new B();
B b = new B();
System.out.println(a);
System.out.println(b);
}
}

Answer

There is only one class name per object in java. If you want to know the name of super class, you have to use: getClass().getSuperclass().getSimpleName().

Since both objects are new B(), doesn't matter if you are calling super.toString() or toString(), both will return the name of class B, because getClass() return always the name of the class that you created by using new.