Casting an object in inheritance, why this conclusion?

There is a class T:

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

Grade G:

public class G extends T
{
     public G(String name)
     {
          super(name);
     }
     public String toString()
     {
          return "G:" + super.toString();
     }
}

When i started

G a3 = new G("me");
System.out.println((T)a3)

He is typing G:T:me.

I do not understand why. I thought he would print T:me. I affirm this because it was distinguished as an object of T. And therefore, using the toString()class T. However, I am wrong. Why is this happening?

I know that there are no good names for classes, it is a question of understanding polymorphism and inheritance, and not just for writing the specific code that I need.

+4
source share
3 answers

, - . () . .

:

 public String toString()
 {
      return "G:" + super.toString();
 }

toString , ( ).

+3

toString() G T, . . , T toString(), T, / G toString() - - , .

+4

G a3 = G ( "me" );

T, G.

public T(String name)
{
    this.name = name;
    // so, this.name gets initialised to me.
}

public G(String name)
 {
      super(name);
 }

, toString(), , , System.out.println((T)a3) a3 . a3 ( println() Object), a3 .

, toString() , G:T:me..

+3

All Articles