+ 1
Protected attributes modified outside class?
I made the following modification to the example code. What I realize is that the value of d.legs can be changed in the main(). So, the question is on how to modify the access specifier of subclass variables/functions? class Animal { protected int legs; public void eat() { System.out.println("Animal eats"); } } class Dog extends Animal { Dog() { legs = 4; } } class MyClass { public static void main(String[ ] args) { Dog d = new Dog(); d.legs = 5; System.out.println(d.legs); d.eat(); } } // Outputs: // 5 // Animal eats
1 Answer
0
This is because a protected member is available within the same package. MyClass, Animal, and Dog are all part of the default package in this code.
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html