Hamad
Hamad

Reputation: 13

protected and package access

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!

Upvotes: 0

Views: 91

Answers (2)

Makoto
Makoto

Reputation: 106528

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.

Upvotes: 0

A--C
A--C

Reputation: 36449

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.

Upvotes: 5

Related Questions