Reputation: 6810
I'm pretty sure I have the Inheritance overriding right, but I was hoping for confirmation:
class C1 {
public int relation( C1 MyC2 ){
//Do stuff
}
}
class C2 extends C1{
public int relation( C2 MyC2){
//Do stuff
return super.relation((C1) MyC2);
}
}
My understanding is that C2#relation() is not actually overriding C1#relation, and thus the following statements are all legal:
MyC1_1.relation(MyC1_2); //Calls C1#relation()
MyC2_1.relation(MyC1_1); //Calls C1#relation()
MyC2_1.relation(MyC2_2); //Calls C2#relation()
While the following is erroneous
MyC1_1.relation(MyC2_1);
If I'm right, then great. Otherwise, I'd love to know why...
Upvotes: 1
Views: 1824
Reputation: 41498
In order to override a method, it must have a signature which is a subsignature of the overridden method's signature. As per Java Language Specification:
The signature of a method m1 is a subsignature for the signature of a method m2 if either:
- m2 has the same signature as m1, or
- the signature of m1 is the same as the erasure of the signature of m2.
This basically means that methods must have the same name and arguments (and also taking into account type erasure).
Therefore in your case relation(C1 c1)
can't be overridden by relation(C2 c2)
. This means that class C1 has only the first method, and C2 has both. That's why your assumptions are absolutely correct, except for the last one (MyC1_1.relation(MyC2_1)
), which is a correct statement too. C2 is a subclass of C1 and therefore C2 can be used wherever C1 can.
Upvotes: 6
Reputation: 5860
All method are correct:
Because this is NOT override, this is overload
"public int relation( C1 MyC2 )" will not be overridden by "public int relation( C2 MyC2)".
You can just add @override above "public int relation( C2 MyC2)"
Upvotes: 1
Reputation: 26871
I'd say that the second instruction from the first batch:
MyC2_1.relation(MyC1_1); //Calls C1#relation()
Is illegal, and the one that you suspect as illegal is correct.
This is, because C2 is more than C1 (it has all that C1 has, plus something more) because it extends
C1 - so, everywhere you expect a C1, a C2 will be ok also.
Meanwhile, C1 is less than C2, for the 'revert' of the above reason, so where a C2 is expected, a C1 will not be enough.
Upvotes: 0