java 带有嵌套类的抽象类,这可能吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5317325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Abstract class with nested class, is this possible?
提问by providence
If I write an abstract class, then nest a class in the abstract class, will I have access to its methods in any subclasses of the abstract class? I cannot find the answer anywhere..
如果我写一个抽象类,然后在抽象类中嵌套一个类,我是否可以在抽象类的任何子类中访问它的方法?我在任何地方都找不到答案..
采纳答案by krock
Of course, access modifiers on inner classes obey the same rules as on fields and methods. It does not matter whether your class is abstract or concrete, as long as the nested class is either public
, protected
or the subclass is in the same package and the inner class is package private (default access modifier), the subclass will have access to it.
当然,内部类的访问修饰符遵循与字段和方法相同的规则。不管你的类是抽象类还是具体类,只要嵌套类是public
,protected
或者子类在同一个包中并且内部类是包私有的(默认访问修饰符),子类就可以访问它。
public abstract class AbstractTest {
// all subclasses have access to these classes
public class PublicInner {}
protected class ProtectedInner {}
// subclasses in the same package have access to this class
class PackagePrivateInner {}
// subclasses do not have access to this class
private class PrivateClass {}
}
回答by binuWADa
class Abstract {
modifier1 class Nested { modifier2 int i = 0; }
Abstract() {
Nested n = new Nested();
n.i = 1;
}
}
class Sub extends Abstract {
Sub() {
Nested n = new Nested();
// have access as long you not choose "private"
// for `modifier1` or `modifier2`:
n.i = 5;
}
}
回答by Pa?lo Ebermann
If the nested class is at least protected, we can access its methods (as long as the methods are public or we are in the same package and they are not private).
如果嵌套类至少是受保护的,我们就可以访问它的方法(只要这些方法是公共的或者我们在同一个包中并且它们不是私有的)。
But you could have tried this out yourself easily :-)
但是你可以很容易地自己尝试一下:-)