0

I'm trying to understand the idea of protected and package acesses and I've tried them on the compiler but it kept telling me that there's a problem

public class example{

    int s = example2.v;

    public static void main(String args[]){


    }
} 

public class example2 {

    int v = 0 ;

}

Can anyone help me with this? why it says:

non-static variable v cannot be referenced from a static context.

Variable 's' is not static!

A--C
  • 36,351
  • 10
  • 106
  • 92
Hamad
  • 13
  • 6

2 Answers2

5

You are trying to reference v in a static manner, that's the problem. Whenever you do ClassName.fieldName that means you're acessing the resource in a static manner. You first have to instantiate the class then do myReferenceVariable.fieldName

public class example{
    example2 myExample = new example2();
    int s = myExample.v;

This should work.

Also keep in mind Java naming conventions have class names start with a capital. Not an issue of compliation, but of readability.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • Thank you! That's weird because in my java book it says that I can access it by name! – Hamad Jan 04 '13 at 02:11
  • @HamadBinAbdullah no problem! It may have been a typo on their side. – A--C Jan 04 '13 at 02:18
  • I don't know, it's Absolute Java fourth edition by PEARSON. They repeated it many times! Sorry man for the click, that was disrespectful of me not only to you, to other people who answered me since I'm new at this. – Hamad Jan 04 '13 at 02:31
0

No, s is most definitely not static. But neither is v. This is what your compiler is telling you.

Since the variable is indeed package scope, you can instantiate a new example2 class and call it directly.

new example2().v;

In general, you'd want to use getters and setters in the future. This allows for encapsulation and information hiding, as that variable v is completely open to be modified by any other class in that package.

Makoto
  • 104,088
  • 27
  • 192
  • 230