0
  1. I am overriding 2 methods of parent in child class and I'm not getting how Object ooj = new String("abc"); is working

  2. as per I'm considered runtime object is of string type but when I pass obj to function it invokes the method with Object type


PARENT CLASS
public class Parent {
    public void function(Object obj) {
        System.out.println("I'm  parent Object Type");
    }

    public void function(String str) {
        System.out.println("I'm parent String");
    }
}

CHILD CLASS

public class Chile extends Parent{
    public void function(Object oob) {
        System.out.println("I'm child object");
    }
    public void function(String str) {
        System.out.println("I'm child string");
    }

    public static void main(String[] args) {
        Parent p = new Chile();
        Object obj = new String("Gaurav");
        p.function(obj);
        String str = new String("and");
        p.function(str);

    }
}

My question is why it is invoking Object method rather and why not string on

Ihor Patsian
  • 1,288
  • 2
  • 15
  • 25
Matt Joshi
  • 11
  • 4
  • 1
    Does this answer your question? [Overloaded method selection based on the parameter's real type](https://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type) – IlyaMuravjov Nov 12 '19 at 08:10

1 Answers1

3

My question is why it is invoking Object method rather and why not string on

Because the compiler doesn't know it's a String any more.

The compiler decides which overload to invoke, this isn't decided at runtime. You are passing it a reference to an Object, so it looks for methods which accept Object. It doesn't bother trying to work out if the thing referred to can be some more specific type.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • but the runtime object is of String type and while overriding a method runtime type of object is checked by jvm i thik – Matt Joshi Nov 12 '19 at 12:46
  • now got this i'm actually **overloading** methods again in child class........ this is why it's invoking Object type method........... am i right ?????? – Matt Joshi Nov 12 '19 at 12:51