Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Casting with Method Calls

Tags:

java

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?

like image 678
user2106549 Avatar asked Feb 25 '13 08:02

user2106549


Video Answer


3 Answers

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.

like image 185
masoud Avatar answered Oct 09 '22 21:10

masoud


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.

like image 32
ssedano Avatar answered Oct 09 '22 22:10

ssedano


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.

like image 42
Kishore Avatar answered Oct 09 '22 23:10

Kishore