Java 访问抽象实例变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15656872/
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
Java Access Abstract Instance variables
提问by B T
I have an abstract class
with a variable like follows:
我有一个abstract class
像下面这样的变量:
public abstract class MyAbstractClass {
int myVariable = 1;
protected abstract void FunctionThatUsesMyVariable();
}
Then when I go to instantiate my class
through the following code, myVariable
cannot be seen:
然后当我class
通过下面的代码去实例化我的时候,myVariable
是看不到的:
MyAbstractClass myClass = new MyAbstractClass() {
@Override
protected void FunctionThatUsesMyVariable() {
// TODO Auto-generated method stub
}
};
What am I doing wrong and how can I achieve what I am trying to achieve?
我做错了什么,我怎样才能实现我想要实现的目标?
回答by dcernahoschi
You are declaring myVariable
as having package access and your 2 classes reside in different packages. Thus the variable is not visible to inheriting classes. You can declare it with protected
access to be visible or put the 2 classes in the same package.
您声明myVariable
具有包访问权限,并且您的 2 个类驻留在不同的包中。因此该变量对继承类不可见。您可以将其声明protected
为可见或将 2 个类放在同一个包中。
public abstract class MyAbstractClass {
protected int myVariable = 1;
protected abstract void FunctionThatUsesMyVariable();
}
回答by OldCurmudgeon
Seems to work for me:
似乎对我有用:
public class Test {
public static abstract class MyAbstractClass {
int myVariable = 1;
protected abstract void FunctionThatUsesMyVariable();
}
public void test() {
MyAbstractClass myClass = new MyAbstractClass() {
@Override
protected void FunctionThatUsesMyVariable() {
myVariable = 2;
}
};
}
public static void main(String args[]) {
new Test().test();
}
}
I suspect you are declaring the two classes in different packages. If that is what you want then you should make the variable protected
(or public
if you must). Alternatively - obviously - put them in the same package.
我怀疑您在不同的包中声明了这两个类。如果这是您想要的,那么您应该创建变量protected
(或者public
如果必须)。或者 - 显然 - 将它们放在同一个包中。
回答by neutrino
Declare your variable as protected. It's package-private
by default.
将您的变量声明为受保护的。这是package-private
默认的。
回答by Kafkaesque
Because you're still subclassing/extending the abstract class and unless you make it protected, the field isn't inherited.
因为您仍在对抽象类进行子类化/扩展,除非您对其进行保护,否则该字段不会被继承。