Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using inherited overloaded methods

Tags:

I have two classes:

public class ClassA {     public void method(Number n) {         System.out.println("ClassA: " + n + " " + n.getClass());     } } 

and:

public class ClassB extends ClassA {                 public void method(Integer d) {         System.out.println("ClassB: " + d + " " + d.getClass());     } } 

But when I run:

ClassA a = new ClassB();  a.method(3); 

I get:

ClassA: 3 class java.lang.Integer 

My question is, why isn't ClassB's method being used? a is an instance of ClassB, and ClassB's method() has an Integer parameter...

like image 284
Federico Avatar asked Oct 11 '12 04:10

Federico


People also ask

Can an inherited method be overloaded?

Yes of course, overloading in inheritance class is possible in Java. Java compiler detect that add method has multiple implementations. so according to the parameter java compiler will determines which method has to be executed. class Parent { public void add(int a) { System.

Does overloading work with inheritance in C++?

The reason is the same as explained in the case of the C++ program. In C#, just like in C++, there is no overload resolution between class Base and class Derived. Also, there is no overloading across scopes and derived class scopes are not an exception to this general rule.


1 Answers

My question is, why isn't ClassB's method being used?

Not true. The method used is ClassB's method, which it inherited from ClassA.


I think the main reason behind the confusion here is the fact that the method actually is not overridden, instead it is overloaded. Although Integer is a subtype of Number, since method parameter is invariant in Java, the method public void method(Integer d) doesn't override the method public void method(Number n). So, ClassB ends up having two (overloaded) methods.

Static binding is used for overloaded methods, and the method with most specific parameter type is chosen by the compiler. But in this case, why does the compiler pick public void method(Number n) instead of public void method(Integer d). That's because of the fact that the reference that you are using to invoke the method is of type ClassA.

ClassA a = new ClassB(); //instance is of ClassB (runtime info) a.method(3);             //but the reference of type ClassA (compiletime info) 

The only method that ClassA has is public void method(Number n), so that's what the compiler picks up. Remember, here the expected argument type is Number, but the actual argument, the integer 3, passed is auto-boxed to the type Integer. And the reason that it works is because the method argument is covariant in Java.

Now, I think it's clear why it prints

ClassA: 3 class java.lang.Integer

like image 194
13 revs, 2 users 94% Avatar answered Oct 09 '22 17:10

13 revs, 2 users 94%