0

I have two public classes class A and B.

public class A{
protected int x;

}

public class B{
A a = new A();
a.x // still possible even though its protected

}

In class A I define a protected variable, but I can still access this variable in B. Why, when it's protected?

I heard it is because they are in the same package, but this makes me confused. I didn't even create a package yet so how does protected work in this case? Are the two classes of the same non-existent package if I don't create packages for them to be in?

I tried outputting in both classes with

this.getClass().getPackage()

and it both gives me "null". So I don't understand what is going on here. are they in the same package or not?

user5846939
  • 415
  • 4
  • 11
  • 1
    Two classes in the null package are still in the same package. – SLaks May 27 '16 at 14:50
  • So is the protected variable visible because they both are in the same unnamed package? – user5846939 May 27 '16 at 14:50
  • The JLS specifies that a JVM implementation can support more than 1 default package (why i don't know), but for your purposes here you can assume there's only one and both your classes are in the same package. – Nathan Hughes May 27 '16 at 14:55

0 Answers0