开发者

How to inherit from an Inner Class? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to make an outer class inherited from an inner class

I want to know Can I Inherit some class from Other cl开发者_运维问答ass 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


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


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.


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 {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜