Overloading overridden method in subclass, am I overloading parent method or sub-classes method?
I understand generally what overloading and overriding is.
Overloading - same method different parameters and maybe return type in the same class.
Overriding - in subclass same method signature as in parent but different implementation.
class A {
public void a() {
System.out.println("A.a");
}
}
class B extends A {
public void a() {
super.a();
System.out.println("B.a");
}
public void a(int x) {
}
}
Is method B.a(int x) overloading A.a or B.a?
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methods—they are new methods, unique to the subclass.
Method overriding always needs inheritance. In method overloading, methods must have the same name and different signatures. In method overriding, methods must have the same name and same signature. In method overloading, the return type can or can not be the same, but we just have to change the parameter.
Overloading can happen in same class as well as parent-child class relationship whereas overriding happens only in an inheritance relationship.
When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
You override something that is inherited, so B.a() overrides A.a(). Overriding means to redefine.
Overloading is when your class have more than one definition of the same method name (each with different argument types). In B, the name a is overloaded. There is B.a() and B.a(int x).
Some of the definitions might be inherited. So if you remove B.a(), the class B would still have a method a() since it inherits it from A. And the method name a would still be overloaded in B.
Method B.a(int x)
overloads B.a()
, since method overloading resolution takes place at compile time, and depends on the compile time type of the variable for which you are calling the method.
On the other hand, the decision of which overridden method to execute takes place at runtime, and depends on the run-time type of the instance for which you are calling the method.
You can see that by trying the following code, which won't pass compilation, since class A
has no method of the signature a(int x)
:
A b = new B ();
b.a(4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With