Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method in sub class overloading a method in super class?

Java code:

class P {
    public void hello() {}
}

class C extends P {
    public void hello(String s) {}
}

My question is: Is the hello in class C overloading the one with same name in super class P?

My friend says they are not because the are not in the same class.

like image 907
Freewind Avatar asked Jul 22 '14 09:07

Freewind


1 Answers

Simple Explanation:

I think this question arises because at times we hear the following,

"Method overloading is performed within class. Method overriding occurs in two classes that have inheritance relationship."

The above statement is correct. But your friend is wrong. why?

Because when you extend a class, the subclass have all the methods defined by superclass. It is as if all the methods of superclass have been implemented by the subclass. That means the hello() method has been implemented by the class C as well. Now, you added a method in class C with different parameter (hello(String s)). That means, class C has two methods in all with same name but different parameters and that is "overloading".

Hope it is crystal clear.

like image 59
Jatin Lalwani Avatar answered Nov 07 '22 18:11

Jatin Lalwani