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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jass
  • 3,345
  • 3
  • 24
  • 41
  • 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.) – Sotirios Delimanolis Apr 01 '15 at 15:49
  • You need an instance of the class. It's not static. – Ria Apr 01 '15 at 15:54
  • I am getting error Cannot make a static reference to the non-static field FreshJuice.a – Jass Apr 01 '15 at 15:58

1 Answers1

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
MeshBoy
  • 662
  • 5
  • 9