Sandeep s
Sandeep s

Reputation: 69

Autoboxing and overloading

public class JavaMain {

    public static void main(String[] args) {
        JavaA a = new JavaB();
        a.m1(5);
        a.m1(new Integer(5));
    }

}

class JavaA{

    public void m1(Integer i){
        System.out.println(2);
    }
}

class JavaB extends JavaA{

    public void m1(int i){
        System.out.println(1);
    }

}

Output: 2 2

As per my understanding, output would be "1 2".

1) When I am calling method a.m1(5) from main method. As per overloading concept, class JavaB's method should get executed. but it wont.

Please help me to understand the concept of overloading+autoboxing.

Upvotes: 4

Views: 362

Answers (4)

Przemysław Moskal
Przemysław Moskal

Reputation: 3609

In Java int and Integer aren't the same types when it comes to overriding methods. This means that method m1 from JavaB doesn't override m1 from JavaA. You can check it with the use of @Override annotation - it simply doesn't work here. In compile time these two methods are overloaded, not overriden, so when in your main() method you want to treat a as it is of type JavaA here: JavaA a = new JavaB(); then there is no other choice than calling method from JavaA - polymorphism have no use here.

Upvotes: 0

Eran
Eran

Reputation: 394156

The decision on which overloaded method will be chosen is done at compile time, based on the methods available for the compile time type. Your a variable has a compile type of JavaA, and JavaA only has a single m1 method, so that's the only method that can be chosen.

m1 of JavaB class can't be a candidate, even though the run-time type of a is JavaB.

Therefore you get the output

2
2

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200306

JavaA a = new JavaB();
a.m1(5);
a.m1(new Integer(5));
  • the static type of a is JavaA
  • JavaA declares just one method m1
  • that method accepts an Integer
  • it is applicable to both calls

The method signature is resolved at compile time. The compiler considers only the signatures declared in the static type of the target expression (JavaA in your case).

Upvotes: 5

William Morrison
William Morrison

Reputation: 11006

You are just calling JavaB.m1 twice, since your object is only ever an instance of JavaB. Here's an example which will do what you're wanting.

public static void main(String[] args) {
    JavaA a = new JavaA();
    JavaA b = new JavaB();
    a.m1(5);
    b.m1(new Integer(5));
    //output will be 
    //2
    //1
}

Both objects can act as an object of type JavaA due to polymorphism, but the instance can be of any subclass of JavaA. The overriden implementation of m1 will be called when the actual type is of JavaB. The original implementation will be called when the instance type is JavaA.

Upvotes: 0

Related Questions