Java Access Abstract Instance variables

btalb picture btalb · Mar 27, 2013 · Viewed 12k times · Source

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?

Answer

dcernahoschi picture dcernahoschi · Mar 27, 2013

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();
}