[英]Java Access Abstract Instance variables
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? 我做错了什么,我怎样才能实现我想要实现的目标?
You are declaring myVariable
as having package access and your 2 classes reside in different packages. 您声明
myVariable
具有包访问权限,并且您的2个类位于不同的包中。 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. 您可以将
protected
访问权限声明为可见,或者将2个类放在同一个包中。
public abstract class MyAbstractClass {
protected int myVariable = 1;
protected abstract void FunctionThatUsesMyVariable();
}
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). 如果这是您想要的,那么您应该
protected
变量(如果必须,则public
)。 Alternatively - obviously - put them in the same package. 或者 - 显然 - 将它们放在同一个包装中。
Declare your variable as protected. 将您的变量声明为受保护。 It's
package-private
by default. 它默认是
package-private
。
因为您仍然是子类化/扩展抽象类,除非您将其保护,否则不会继承该字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.