public class T
{
protected String name;
public T(String name)
{
this.name = name;
}
public String toString()
{
return "T:"+this.name;
}
}
public class G extends T
{
public G(String name)
{
super(name);
}
public String toString()
{
return "G:" + super.toString();
}
}
When I run
G a3 = new G("me");
System.out.println((T)a3)
It prints G:T:me
.
I don't understand why. I thought it would print T:me
. I claim this because it was casted as object T. And therefore, using the toString()
of class T. However, I'm wrong. Why does this happen?
I know there are not good names for classes, it's a question about understanding polymorphism and inheritance, not just to write a specific code I need.
The method toString()
in class G overrides the method in class T, so it gets chosen. The static type of the object is used by the compiler to decide which overload of a method to use. It could only make a difference if there were two different toString()
methods defined on T to choose from, and / or G defined another toString()
overload somehow - although it's not really possible when there are no arguments to the method.
The crucial point here is a cast does not change the object in any way. All it does is allow you to treat it as a different (compatible) type. The objects functionality stays exactly the same.
The code:
public String toString()
{
return "G:" + super.toString();
}
completely removes the old toString
to a point where it is no longer accessable at all (mostly).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With