Reputation: 13
Given two abstract classes, AClass1 and AClass2, the first of which has an abstract method using the second of which as a parameter, how do you use subclasses of those abstract classes to work together without Java complaining about unimplemented abstract methods?
public abstract class AClass1 {
...
public abstract void aMethod(AClass2 param1, int param2, ... );
...
}
public abstract class AClass2 {
...
}
public class CClass1 extends AClass1 {
...
public void aMethod(CClass2 param1, int param2, ...) {
...
}
public class CClass2 extends AClass2 {
...
}
I would think that concrete class CClass1 would be OK, but Java balks, requesting that I implement public void aMethod(AClass ...)
.
What am I doing wrong?
Upvotes: 1
Views: 2016
Reputation: 683
I know this question is old now, but I recently had the same problem.
What I did in the end is, I didn't define the abstract class but define a interface for the child classes.
This way you unfortunately can't share method implementations, but you can have a template for them, and depending on your IDE, the methods will be auto-generated for you.
Upvotes: 0
Reputation: 597046
Java supports only covariant return types, not covariant parameter types.
If it were otherwise, imagine that you obtain an instance of the subclass, but refer to it as the abstract class:
AClass1 a = new CClass1();
AClass2 param = new AnotherCClass();
a.aMethod(param); // ClassCastException - can't cast AnotherCClass to CClass2
Upvotes: 0
Reputation: 2245
You have to keep the correct signature in your concrete class:
public abstract void aMethod(AClass2 param1, int param2, ... );
Upvotes: 1
Reputation: 533492
CClass1 must implement a method which can take any AClass2 as you have specificed that it would. You can overload this method, but you have to implement the abstract methods of the parent.
Upvotes: 4