Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing null to the overridden method when the difference between methods is the parameter subtype [duplicate]

Tags:

java

oop

jvm

OUTPUT:B

Why does virtual machine call this method f(null){System.out.println("B");}?

Why not f(null){System.out.println("A");}

public class Test{

    public static class A {}
    public static class B extends A {}

    public void f(A a) {System.out.println("A");}
    public void f(B a) {System.out.println("B");}

    public static void main(String[] args) {
        new Test().f(null);
    }
}
like image 752
alexjavajunior Avatar asked Sep 27 '13 09:09

alexjavajunior


People also ask

Can an overridden method have different parameters?

No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods.

Do overriding method must have same return type or subtype?

Instance Methods The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.

Can the overridden methods in case of inheritance have different return type?

Yes. It is possible for overridden methods to have different return type . But the limitations are that the overridden method must have a return type that is more specific type of the return type of the actual method.

Can we override a method by using same method name and arguments but different return types explain with examples?

Overloading with same arguments and different return type −No, you cannot overload a method based on different return type but same argument type and number in java. same name. different parameters (different type or, different number or both).


1 Answers

The method with most specific parameter type is called. Thats the rule This is from JLS section 15.12.2.5

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

like image 62
Prasad Kharkar Avatar answered Oct 05 '22 04:10

Prasad Kharkar