-1

these days i read the java tutorials.And in the section "Controlling Access to Members of a Class" i have some trouble in the access level of modifier "protected".let me show the code:

package PackagesOne;

public class Alpha {
   protected String name;
}



package PackagesTwo;

import PackagesOne.Alpha;

public class AlphaSub extends Alpha {
   public static void main(String[] args){
       Alpha alpha = new Alpha();
       String name = alpha.name;
   }
}

and in the PackagesOne i declare the String name of the modifier "protected",in the pacagesTwo the AlpaSub is subclass of the Alpha in the packagesOne.And my question is that in the java tutorial Controlling Access to Members of a Class,it say that the subclass in others packages can access the class members which are modified with protected.but i can not do it, when i javac the AlphaSub,it have error.

thinkinjava
  • 95
  • 1
  • 6
  • 1
    "it have error" is *never* enough information. *Always* give the error message. And in this case, read http://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.6.2 – Jon Skeet Dec 12 '14 at 13:08
  • thanks a lot, and elder i want to make friends with you to, can you give me some inofrmation about you like email? – thinkinjava Dec 12 '14 at 13:20

3 Answers3

1

That's because you are creating an Alpha object try creating a AlphaSub object:

AlphaSub alphaSub = new AlphaSub();
String name = alphaSub.name;

marking a variable protected does allows it to get accessed outside the package but only through the subclass's object and not the parentClass's object

Sarthak Mittal
  • 5,794
  • 2
  • 24
  • 44
0

You are not accesing it in the correct way. You need to create an AlphaSub object.

MihaiC
  • 1,618
  • 1
  • 10
  • 14
0

Protected members are available within subclass as the members of sub-class only. So within AlphaSub its accessible as this.name. But not as alpha.name, because name is not public.

Manojkumar Khotele
  • 963
  • 11
  • 25