如何继承内部类?
可能的重复:
如何使外部类从内部类继承类
我想知道我可以从其他类内部类继承一些类吗?
我想运行下面的代码,但出现错误。
public class Computer {
int model;
Computer(int i) {
model = i;
}
public class HardDrive {
int size;
public HardDrive(int i) {
size = i;
}
public HardDrive() {
size = 40;
}
}
}
主要是:
class SCSI extends Computer.HardDrive {
SCSI(Computer c) {
c.super(80);
}
}
我收到此错误:
没有类型的封闭实例 inside.inherit.Computer 位于范围内
Possible Duplicate:
How to make an outer class inherited from an inner class
I want to know Can I Inherit some class from Other class inner class?
I want to run below code but I get error.
public class Computer {
int model;
Computer(int i) {
model = i;
}
public class HardDrive {
int size;
public HardDrive(int i) {
size = i;
}
public HardDrive() {
size = 40;
}
}
}
And the main is:
class SCSI extends Computer.HardDrive {
SCSI(Computer c) {
c.super(80);
}
}
I get this error:
no enclosing instance of type
inner.inherit.Computer is in scope
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果
SCSI
不是Computer
中的另一个内部类,则必须将HardDrive
设为静态。If
SCSI
is not another inner class inComputer
, you have to makeHardDrive
static.我认为如果你将 HardDrive 设为内部静态类,它应该可以工作。原因是“普通”内部类与封闭类的实例有关系(例如,您可以通过在
HardDriveComputer.this
来访问 Computer 的“this” code>),这就是编译器希望 Computer 实例位于范围内的原因。如果将HardDrive设置为静态,则内部类和外部类的实例之间不存在这种联系,因此您可以不受限制地继承它。I think it should work if you make HardDrive an inner static class. The reason is that "normal" inner classes have have a relation to an instance of the enclosing class (e.g. you can access the "this" of Computer by writing
Computer.this
inHardDrive
), so that's why the compiler wants a Computer instance to be in scope. If you make HardDrive static, no such connection between instances of the inner class and the outer class exist, so you can inherit from it without limitation.似乎对我来说效果很好(参见)。确保 SCSI 与计算机位于同一命名空间中,否则使用
Seems to work fine for me (See). Make sure SCSI is in the same namespace as Computer or else use