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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:26:15  来源:igfitidea点击:

Java Access Abstract Instance variables

javaabstract-classmember-variables

提问by B T

I have an abstract classwith a variable like follows:

我有一个abstract class像下面这样的变量:

public abstract class MyAbstractClass {

    int myVariable = 1;

    protected abstract void FunctionThatUsesMyVariable();
}

Then when I go to instantiate my classthrough the following code, myVariablecannot 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 myVariableas 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 protectedaccess 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 publicif you must). Alternatively - obviously - put them in the same package.

我怀疑您在不同的包中声明了这两个类。如果这是您想要的,那么您应该创建变量protected(或者public如果必须)。或者 - 显然 - 将它们放在同一个包中。

回答by neutrino

Declare your variable as protected. It's package-privateby 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.

因为您仍在对抽象类进行子类化/扩展,除非您对其进行保护,否则该字段不会被继承。