Polymorphism of java thinking

consider the following code:

public class A{
    private int num;
    public A(int n){
        num = n;
    }
    public int getNum(){
        return num;
    }
    public boolean f(A a){
        return num == a.num * 2;
    }
}

public class B extends A {
    public B(int n) {
        super(n);
    }

    public boolean f(B b) {
        return getNum() == b.getNum();
    }
}

public class Main
{
    public static void main(String[] args){
        A y1 = new B(10);
        B y2 = new B(10);
        System.out.println("y1.f(y2) is: "+y1.f(y2));
    }
}

I don’t understand why the method fworks for the class A(and prints false), but not Bbecause it y1has a type at runtime Band should go to the method fin the class B?

+4
source share
2 answers

note that the parameters in class B and class A in the f-function are different. this is the reason that the "gravitational minimum" does not exist here, and this time it enters the function Af

+1
source

Is the run-time reason y1 is of type B and should go to method f in class B?

<Not p> No:
  • B.f() A.f(), . .
  • ,

B.f(), A, B, , . , .

.

+8

Source: https://habr.com/ru/post/1547713/


All Articles