简体   繁体   中英

How to do Java polymorphism

Edit: should be a2 = new B() I don't understand why the result for a2.foo(b) is 3 in the following practice question.

I thought with polymorphism, the dynamic types method would run with the method signature that takes the argument that corresponds with the static type.

public class A {
    public int foo(Object o) {
        System.out.println(1);
        return 1;
    }

    public int foo(A a) {
        System.out.println(2);
        return 2;
    }
}

public class B extends A {
    public int foo(A a) {
        System.out.println(3);
        return 3;
    }

    public int foo(B b) {
        System.out.println(4);
        return 4;
    }

public static void main(String[] args) {
        A a2 = new B();
        B b = new B();
        a2.foo(b);
    }
}


The answer my school has given is a2.foo(b) returns 3, however I thought it would return 4.

Thanks in advance!

EDIT: As the question was changed, the answer is now 3 as A.foo(A) is called but overridden.


If a2 was a B then the overridden method would be used, never an overloaded method.

But a2 is an A and which class only has one method foo(A) which can be called, so it prints 2

In short, only the type of this on the left hand side of . will change the choice of method called.

a2 is obviously A , therefore A#foo is executed. It is possible (compiles and executes) since B is instance of A .

Since A#foo is executed, answer is 2 (not 3 and not 4 ).

There are two things going on here:

  1. Overloading
  2. Overriding

Overloading is about having two different methods in the same class with the same name but different argument types (so they are different). Overriding and polymorphism is about having the same single method in two different classes.

Classes A and B both overload the foo method: they have two methods with the same name. In A one method takes Object as a parameter and one takes A as a parameter. In B one takes A as a parameter and one takes B . Of these four methods, two are the same ( foo(A) ).

The foo(A) method in B overrides the foo(A) method in A . The foo(B) method however is a different method.

So when you call a2.foo(b) you are calling the foo(A) method. It must be, as a2 is declared as A and A doesn't have a A.foo(B) . Since a2 is an actually an object of type B , you are calling B.foo(A) as it overrides A.foo(A) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM