2

I have an abstract class with a variable like follows:

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:

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?

btalb
  • 6,937
  • 11
  • 36
  • 44

4 Answers4

7

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.

public abstract class MyAbstractClass {

    protected int myVariable = 1;

    protected abstract void FunctionThatUsesMyVariable();
}
dcernahoschi
  • 14,968
  • 5
  • 37
  • 59
  • That is only true if the two classes are in different packages. – OldCurmudgeon Mar 27 '13 at 10:50
  • Thanks, your answer is correct. Just one more question. `myVariable` is a `File` and now it complains about `the local variable may not have been initialized` but the constructor does initialise it? If I did that in a normal class it would not complain, why is it here? – btalb Mar 27 '13 at 12:45
  • Post the exact the code of the two classes and indicate the line where the compiler complains. But I think it should be another question. – dcernahoschi Mar 27 '13 at 13:45
2

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
1

Declare your variable as protected. It's package-private by default.

neutrino
  • 2,297
  • 4
  • 20
  • 28
1

Because you're still subclassing/extending the abstract class and unless you make it protected, the field isn't inherited.

Kafkaesque
  • 1,233
  • 9
  • 13