8

I have 3 classes GrandParent, Parent and Child, where Child extends Parent and Parent extends GrandParent

public class Main {
    void test(GrandParent gp){System.out.println("GrandParent");}
    void test(Parent p){System.out.println("Parent");}

    public static void main(String args[]){
        GrandParent obj = new Child();
        Main mainObj = new Main();
        mainObj.test(obj);  // This calls test(GrandParent gp)

        mainObj.test(new Child()); // This calss test(Parent gp)
    }
}

In above code in the 2 calls to test() method both with Child object calls different methods. In one it's doing compile-time and in other run-time binding. This sounds little weird to me. How would you explain this?

Learner
  • 1,503
  • 6
  • 23
  • 44

3 Answers3

13

Method overloading is compile-time polymorphism.

Method overriding is runtime polymorphism.

In your case, you are overloading two instance methods of class Main.

However, since I presume in your context Child extends Parent, new Child() instanceof Parent == true hence an instance of Child is a valid argument for the method test with argument type Parent.

In your first case, you pass a reference type GrandParent in the method test, and the exact type is found.

In your second case, you pass a reference type Child in the method test. The closest match is Parent, hence test(Parent p) is invoked.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

I think you're getting confused with your hierarchy.

The fact you say: Child extends Parent - this means that a Child "is a" Parent.

Given the fact this does not make sense in the "real world" - it does, however, make sense in your code - you are supplying a Child object to the void test(Parent p) method - and since a Child is a Parent - this is why System.out.println("Parent") is invoked.

Davie Brown
  • 717
  • 4
  • 23
  • 2
    But a `Child` is also a `Grandparent` in this hierarchy, right? So why is the `Parent` method invoked and not the `Grandparent` method? You're technically right, but you're not quite answering OP's question. – awksp Jun 12 '14 at 15:54
  • I would assume that given another matching declaration, say - void test(Object o) that supplying a Child object would then invoke this method, due to the fact the Child class implicitly extends Object. I could however be wrong. – Davie Brown Jun 12 '14 at 16:00
  • Depending on if I'm thinking the same thing as you, it actually wouldn't, if you did `test(new Child())`. If you assigned `new Child()` to an `Object` and passed that, I think it would. – awksp Jun 12 '14 at 16:01
-1

Overloading means same name different parameter. For example:

      class A {
          public void m1(int a) {
              System.out.println("class A");
          }
          public void m1(int a,int b) {
              System.out.prinln("2 parameter");
          }
      }

This is called method overloading.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
vijay
  • 7
  • 2