Java 抽象类、抽象方法和抽象类参数
给定两个抽象类 AClass1 和 AClass2,其中第一个有一个抽象方法,使用第二个抽象方法作为参数,如何使用这些抽象类的子类来协同工作,而不会让 Java 抱怨未实现的抽象方法?
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 {
...
}
我认为具体的类 CClass1 就可以了,但 Java 犹豫不决,要求我实现 public void aMethod(AClass ...)
。
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
CClass1 必须实现一个可以采用您指定的任何 AClass2 的方法。您可以重载此方法,但必须实现父级的抽象方法。
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.
您必须在具体类中保留正确的签名:
You have to keep the correct signature in your concrete class:
Java 仅支持协变返回类型,而不支持协变参数< /em> 类型。
如果不是这样,想象一下您获得了子类的一个实例,但将其称为抽象类:
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:
我知道这个问题现在已经很老了,但我最近遇到了同样的问题。
我最终所做的是,我没有定义抽象类,而是为子类定义了一个接口。
不幸的是,这样您就无法共享方法实现,但您可以拥有它们的模板,并且根据您的 IDE,系统会自动为您生成方法。
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.