0

Why is it possible to access a protected atribute?

class Test{ protected int a; public Test(){ a = 9; } } public class Program { public static void main(String[] args) { Test t = new Test (); System.out.println (t.a); } } this results in: 9 why not an error, or null? protected members should not be accessible from outside of the class, right?

24th Feb 2017, 5:18 PM
Tomasz
Tomasz - avatar
4 Answers
+ 1
Thats private not protected. protected is an access modifiers that allows own class or any other derived class to access it
24th Feb 2017, 5:41 PM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar
0
Corsair Alex: but the class Program didn't extend the class Test.
26th Feb 2017, 7:46 AM
Tomasz
Tomasz - avatar
0
ok. just found out, that protected memebers can be accessed by another class in the same package. if I move the Test class to another package, the same code will give an error.
26th Feb 2017, 7:50 AM
Tomasz
Tomasz - avatar
0
Seems like you misunderstood between the concept of inheritance and object initialization. In your code, you are initializing an object t of class Test, ie. Test t= new Test(); Just as you mentioned previously, protected class members can be accessed by ITSELF or any other classes that derived from your base Test class, which is none in your case. Since you are initializing an object from class Test, it is correct to access any public or protected members.
26th Feb 2017, 4:08 PM
Alex Soh Chye Wat
Alex Soh Chye Wat - avatar