7

Suppose I have the following classes

class A{
    public method(A a) {
        System.out.println(3);
    }
}

class B extends A{
  public void method (A a) {
        System.out.println(2);
  }
  public void method (B b) {
        System.out.println(1);
  }
}

A obj = new B();
obj.method( (B) obj);
((B) obj).method( (B) obj);

The first method call prints out 2 while the second method call prints out 1. Why don't both method calls print out 1?

user2106549
  • 71
  • 1
  • 2

3 Answers3

4

void method (B b) of B is totally unknown for its parent A.

It's logical, because in obj.method((B) obj);, the type of obj is A which in polymorphism rule it can just call void method(A a) version of class B.

class B extends A {

    // This is an overridden method visible to A
    public void method(A a) {
        System.out.println(2);
    }

    // This is an overloaded method unknown from A
    public void method(B b) {
        System.out.println(1);
    }
}

You can read this SO answer which explained Override vs. Overload.

Community
  • 1
  • 1
masoud
  • 55,379
  • 16
  • 141
  • 208
3

Because java selects the method to call in compile time. And the compiler only take into account the "left side" of an assignment.

So when you type A obj = new B() the compiler only "sees" the methods in class A.

ssedano
  • 8,322
  • 9
  • 60
  • 98
  • Well... the compiler only "sees" that such methods are defined, but calls the methods of the object, which in the case are the ones of class B because it has the same method with the same arguments. That happens because all methods in java are virtual. – Kokozaurus Feb 25 '13 at 08:33
1

The first method call is done using object reference of type A, so the corresponding method, which could be overridden, is called.

In the second case first the cast is done to type B, so corresponding method defined in class B ,i.e,

method (B b)

is called.

Kishore
  • 819
  • 9
  • 20