Java behavior when method signatures are similar in Parent and Child
I have the
following 3 cases where methods in parent and child classes have the same name and different parameters.
Case 1:
class Parent
{
public void hello(Object obj)
{
System.out.println("Parent");
}
}
class Child extends Parent
{
public void hello(String obj)
{
System.out.println("Child");
}
}
Case 2:
class Parent
{
public void hello(String obj)
{
System.out.println("Parent");
}
}
class Child extends Parent
{
public void hello(Object obj)
{
System.out.println("Child");
}
}
Case 3:
class Parent
{
public void hello(Object obj)
{
System.out.println("Parent");
}
public void hello(String obj)
{
System.out.println("String in Same Class");
}
}
class Child extends Parent
{
}
There is main() as follows:
public static void main(String[] args) {
Child c = new Child();
c.hello(null);
}
Output from Case 1:
Child
Output from case 2:
Parent
Output from case 3:
String in Same Class
I observed in all three cases every time a method with a String parameter is called. It doesn’t matter if it’s in Child or Parent. I’m really confused because “null” should create some ambiguity, or a subclass’s method should be chosen as its child object. Why does this behavior occur?
Solution
According to the Java language specification §15.12.2.5 choose the most specific method
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.
In your case, there is a way to accept an Object
and a method to accept a String
. Since String
is a subclass of Object
, which is more specific, it will be selected. For more details on what is considered more specific, see the language specification.