1

I have done some research but I am no able to find why runtime polymorphism is not taking place in example below. According to my understanding foo(int a) should have been called in child.But out put is "Parent with long".Can someone throw light on this?

class Parent {
public void foo() throws RuntimeException {
    System.out.println("Parent with no Parameter");
}

public void foo(long a) {
    System.out.println("Parent with long");
}
}

class Child extends Parent {
public void foo() {
    System.out.println("Child with no parameter");
}

public void foo(int a) throws RuntimeException {
    System.out.println("Child with int");
}
}

class Demo {
public static void main(String... args) {
    Parent p = new Child();
    int a = 10;
    p.foo(a);
}
}

Output:

Parent with long

Vishal
  • 296
  • 3
  • 11

4 Answers4

2

Polymorphism only applies when methods have the exact same signature (same number and types of parameters).

NineBerry
  • 26,306
  • 3
  • 62
  • 93
2

What you have is Parent with 2 methods: foo(long) and foo(). And Child that inherits from its parent and add two new different methods: foo(int) and (that one overloads existing methods) foo()(that one overrides the inherited one).

There is different mechanisms: what happens at compile time, and what happens at runtime. At compile time, the compiler will only look accordingly to variable types. At runtime, the execution env. will look at object types.

Now when compiling the call p.foo(a), compiler will look at the type of p, which is Parent and look in Parent class for a corresponding callable method. It finds foo(long) and then generates a dynamic call to a method foo(long) with a cast from int to long to the real object at runtime (of type Child). But this object has only one such method, the one in Parent, so this one will be called.

Change Child's foo(int) into foo(long) and you will have what you wanted.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
0

As you said polymorphism is correct. What you seeing is compile time polymorphism which is overloading.

The method from Child already been decided at compile time cause there is no equivalent method define in parent and no ovveriding (runtime polymorphism) applied .

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

In java polymorphism works in down to top mechanism.. you see.. when you are creating the child object, you are actuality creating a patent object.. and it will never give an error as your child extends to patent. So.. you are actually creating a patent object.. not a child object at all.. that's why it's executing parents' method.. if you would like to see how polymorphism works.. then just create Child object =new Child (). And then pass Long or int variable.. Hope that helps

androCoder-BD
  • 498
  • 7
  • 13