Java – why the super class method?

class One { 
class One { 
  public void doThing(One o) {System.out.println("One");}
}

class Two extends One{
  public void doThing(Two t) {System.out.println("Two");}
}

public class Ugly {
  public static void main(String[] args) {
    Two t = new Two();
    One o = t;
    o.doThing(new Two());
  }
}

Results: 1

class One { 
  public void doThing(One o) {System.out.println("One");}
}

class Two extends One{
  public void doThing(Two t) {System.out.println("Two");}
}

public class Ugly {
  public static void main(String[] args) {
    Two t = new Two();
    One o = t;
    t.doThing(new Two());
  }
}

Results: II

I know that at runtime, even if the object reference is a supertype, the actual object type will be known and the actual object's method will be called However, if so, the dothing (two T) method should be called at runtime, instead of the superclass method dothing (one o) I'd be happy if someone explained

Print "two" in the second code

Problem: calling it from a superclass reference calls dothing (one o) when calling it from a subclass reference calls dothing (two o)

Note: I know I'm overloaded, not riding I have edited my question to make it clearer

Solution

The method dothing () has different method signatures in one and two

One.doThing(One one)
Two.doThing(Two two)

Since the signatures don't match, two Dothing (two) will not overwrite one Dothing (one), because o is of type one, call one doThing().

Also note that one Dothing (one) can use two as one Dothing (one) as a parameter of two extension one

In the first case, when you do this

Two t = new Two();
One o = t;
o.doThing(new Two());

So o is one and two An instance of dothing (two) is not available for O, so one is called doThing(One)

In the second case,

Two t = new Two();
One o = t;
t.doThing(new Two());

T is an example of two, so it is called two doThing(Two).

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>