如何继承内部类?

发布于 2024-11-02 14:56:23 字数 779 浏览 5 评论 0原文

可能的重复:
如何使外部类从内部类继承类

我想知道我可以从其他类内部类继承一些类吗?
我想运行下面的代码,但出现错误。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

离笑几人歌 2024-11-09 14:56:23

如果 SCSI 不是 Computer 中的另一个内部类,则必须将 HardDrive 设为静态。

If SCSI is not another inner class in Computer, you have to make HardDrive static.

非要怀念 2024-11-09 14:56:23

我认为如果你将 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 in HardDrive), 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.

黯然 2024-11-09 14:56:23

似乎对我来说效果很好(参见)。确保 SCSI 与计算机位于同一命名空间中,否则使用

class SCSI extends <namespace>.Computer.HardDrive {

Seems to work fine for me (See). Make sure SCSI is in the same namespace as Computer or else use

class SCSI extends <namespace>.Computer.HardDrive {
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文