0

I am trying to access int a= 10 variable in child class but getting error:

Cannot make a static reference to the non-static field FreshJuice.a

Following is my code.

class FreshJuice {
    enum FreshJuiceSize{SMALL,MEDIUM,LARGE};
    FreshJuiceSize size;
    int a   =   10;
}

public class Index extends FreshJuice {

    enum programmingLanguage{PHP,Java,Dotnet,HTML};

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(FreshJuice.FreshJuiceSize.SMALL);
        System.out.println(programmingLanguage.PHP);
        System.out.println(FreshJuice.a); //getting error in this line
    }

}

I want to directly access int variable of FreshJuice class in child class. How can i achieve this target?

3
  • 1
    Why are you being abstract and secretive? You got an error. Tell us exactly what error you got. But, before you do that, check that others haven't had the same error. (Hint: they have.) Commented Apr 1, 2015 at 15:49
  • You need an instance of the class. It's not static. Commented Apr 1, 2015 at 15:54
  • I am getting error Cannot make a static reference to the non-static field FreshJuice.a Commented Apr 1, 2015 at 15:58

1 Answer 1

0

First create an instance of FreshJuice class:

FreshJuice fj = new FreshJuice();

Now you can access the variable a .

But if you set your variable as private int a=10; Then you can't access that still. That's why it is good practice to use getter and setter methods to access those private variables.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.