4

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)); } } 

What I don't understand is why the method f is running for class A (and printing false) and not B, cause in run time y1 is of type B, and should go down to method f in class B?

4
  • What is a C object? I'm guessing it's another subclass of A, but it's not shown anywhere. Commented Jul 9, 2014 at 10:36
  • 1
    YES cause is not related to the question Commented Jul 9, 2014 at 10:36
  • @DanTemple: Given that z1 and z2 aren't used anywhere, they're irrelevant (and should be removed from the question). Commented Jul 9, 2014 at 10:36
  • Fair, so as @JonSkeet points out, they shouldn't be in the question in that case. Commented Jul 9, 2014 at 10:39

2 Answers 2

8

cause in run time y1 is of type B, and should go down to method f in class B?

No:

  • B.f() doesn't override A.f() because the parameter types are different. It overloads it.
  • Overloads are picked at compile-time, not at execution time

If you change B.f() to accept a parameter of type A rather than B, you'll see it get executed. That doesn't depend on the execution-time type of the argument, but on the execution-time type of the target of the call.

The method implementation which is chosen never depends on the execution-time type of an argument.

Sign up to request clarification or add additional context in comments.

Comments

1

pay attention that the parameters in class B & class A in f function are diffrent. that is the reason that the "gravity low" dont exist here and this time it enter to the A.f function

2 Comments

Sorry, I don't understand this at all. What does "gravity low don't exist here" mean?
A y1 = new B(10); --> its polymorpishem. when y1 call the f method he goes to the method in class A , but because he is also B type he "looks down" in the inheritance and check if there is the same method "down". this time beacuse there is overloading and not overriding he exrcuting the method in class A.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.