2

Given the following code, why is it that I'm able to access a protected variable in a class that is neither in the same package nor extends the class that declared the variable?

public class B{
     protected String s = "B1";
     public B() {};

}

public class P{
     public void out(Object o){
         System.out.println(o);}
}

public class M{
    B b = new B();
    P.out(b.s);}

Why can the out method access b.s?

eager2learn
  • 1,447
  • 4
  • 24
  • 47
  • It's not the `P#out` method which "accesses" the variable, but the class `M`. – qqilihq Feb 19 '14 at 10:45
  • 2
    its strange that the P.out can be done without P.out being static :D. – chillworld Feb 19 '14 at 10:48
  • Since your code is not complete, I can't be certain, but B and M are probably in the same package. – Pablo Feb 19 '14 at 10:49
  • Yeah and no constructor/method either, this is just a hastily thrown together example that does not realistically represent the code that this is being asked about. Post the -actual- code, with package statements. – Gimby Feb 19 '14 at 10:49
  • Add the package statements, otherwise, this question will be closed, as not to have enough information. – Abimaran Kugathasan Feb 19 '14 at 10:52
  • 1
    I'm sorry guys, I assumed that since I did not explicitly create a package, the classes weren't in the same package. I did not know that all classes are automatically put into a default package. Sorry once again, I'm still new to Java. – eager2learn Feb 19 '14 at 10:54

2 Answers2

0

S is accessable because it is protected not private. You can call it through B.

  • that depends all of in what package the class M and B are, without package declaration and real compiling code(this code won't compile!) you can't be sure. – chillworld Feb 19 '14 at 11:03
0

I would guess you are getting package level access. Look here for more information: In Java, difference between default, public, protected, and private

Community
  • 1
  • 1
Jeef
  • 26,861
  • 21
  • 78
  • 156