1

Considering the following:

class Parent {
    public void print(Object s) {
        System.out.println("I am inside Parent Object Method.");
    }
}

public class Child extends Parent{

    public void print(String s) {
        System.out.println("I am inside Child String Method.");
    }

    public static void main(String arg[]) {
        Parent a = new Child();
        a.print(null);
    }
}

Output:

I am inside Parent Object Method

Here JVM is calling Parent Method in place of child method regardless of the logic of "more specific method should be called" in ambiguity.

What would be the reason for this implementation in java?

Sanchi Girotra
  • 1,232
  • 13
  • 13

2 Answers2

3

There is no ovverding involved here. What involved is Overloading. Your Overloaded method with Object called cause the passe value 1 converted to Integer Object and print method of Parent class called since it is available for Child.

There is no ambiguity here cause you overloaded methods with different types.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

1 is not a String, and has no automatic conversion to a String, so it cannot be passed to a method that expects a String argument.

Therefore public void print(Object s) is executed, since an int can be boxed into an Integer, which is an Object.

Try a.print("1"); or even a.print(null); if you want public void print(String s) to be executed.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • if i write `a.print(null);` then also its calling parent method. – Sanchi Girotra May 24 '17 at 11:00
  • @SanchiGirotra I just tested it myself and it prints "I am inside Child String Method.", so you must have made a mistake somewhere. – Eran May 24 '17 at 11:02
  • Mymistake. Edited the question : now reference Object is of parent. – Sanchi Girotra May 24 '17 at 11:07
  • @SanchiGirotra That's a different question. Method overloading resolution is determined at compile time based on the compile time type of the variable for which you are calling the method. Therefore the compiler only sees the method of the parent class. – Eran May 24 '17 at 11:09
  • Firstly here its not method overloading and moreover then also child method is called at run time but why here parent method is called. – Sanchi Girotra May 24 '17 at 11:16
  • @SanchiGirotra Of course it's method overloading. Two methods with the same name and different arguments - that's the definition of method overloading. Child method is only called if the compile time time of the variable is Child, since in that case the compiler has both methods to choose from. – Eran May 24 '17 at 11:18
  • As inheritance is resolved at compile time so both methods will be available at compile time with Child class so now it had 2 methods with same name and different parameters then the most specific method will be called which is `print(String s)` but here `print(Object s)` is called. Please elaborate your answer with example if possible. – Sanchi Girotra Jun 01 '17 at 10:35