Monday, February 2, 2009

Protected Access Modifier Facts

I show an interesting example to the protected access modifier.



Our first file, Animal.java in package world:
01. package world;
02. public class Animal {
03. protected int age;
04. }


Our second file, Animal.java in package africa:
01. package africa;
02. import world.Animal;
03. public class Zebra extends Animal {
04. public void sayAge() {
05. System.out.println("My age is "+age); //Works well, age is protected;
06. }
07. public void sayFriendAge() {
08. Animal friend = new Animal();
09. System.out.println("My fried's age is " + friend.age ); //Compile error, age is accessible
10. // through inheritance
11. }
12. }


Our third file, Lion.java in package africa:
01. package africa;
02. public class Lion {
03. public void sayZebraAge() {
04. Zebra zebra = new Zebra();
05. System.out.println("Zebra's age is " + zebra.age ) ; //Compile error, Zebra and Lion are
06. // in the same package, but age is protected and only available using inheritance, Lion
07. // can't see it.
08. }
09. }

No comments: