Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an object in inheritance, why this output?

There is class T:

public class T
{
    protected String name;
    public T(String name)
    {
        this.name = name;
    }
    public String toString()
    {
        return "T:"+this.name;
    }
}

Class G:

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.

like image 590
Pichi Wuana Avatar asked Dec 25 '22 07:12

Pichi Wuana


2 Answers

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.

like image 64
sisyphus Avatar answered Dec 28 '22 05:12

sisyphus


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).

like image 45
OldCurmudgeon Avatar answered Dec 28 '22 06:12

OldCurmudgeon