Method overloading or overriding?

Viewed 86

We have a Parent and child class, which has method with the same name but argument are as primitive and wrapper. Could someone please explain the reason whether this would be referred as Method Overriding and Method overloading. Running this program would invoke Parent method - which would be overriding and not overloading, looking for explanations.

class Parent {
    public void takeValue(int a) {
        System.out.println("take value method from parent is invoked");
    }
}

class Child extends Parent {
    public void takeValue(Integer a) {
        System.out.println("take value method from child is invoked");

    }

    public static void main(String[] args) {
        Parent p = new Child();
        p.takeValue(new Integer(51));
    }
}
2 Answers

The method is overloaded.

Running this program would invoke Parent method - which would be overriding and not overloading

Yes. You're calling takeValue on a Parent variable, which means that the compiler will look for a signature match on the Parent class. The overload is not even visible here (signatures are matched based on static types, i.e., java finds the method based on the declared data type of the variable on which the method is called, not with the data type of the object assigned to the variable, which would be a runtime thing).

And because public void takeValue(Integer a) is not considered by the compiler when checking the method invocation, p.takeValue(new Integer(51)); is linked to Parent.takeValue(int) by virtue of autoboxing (it would have matched the other method if both of them were visible - or declared in the Parent class in this example).

This is overloading. You have same name but type of input parameters are different.

To confirm that, you will get an error when you try to attach the @Override annotation.

Integer and int are different types.

Related