I have the following two files:
Fruit.java:
package superClass;
public class Fruit {
protected static void printName() {
System.out.println("My name is Khan");
}
}
Apple.java:
package food;
import superClass.*;
public class Apple {
public static void main(String[] args) {
int i, j;
for(i = 0; i < 5; i++) {
for(j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
printName(); // Call inherited member - NO ERROR, expected
Fruit f = new Fruit();
f.printName(); // Call instantiated member - ERROR, expected
}
}
As expected, I do not have access to the protected method printName from the class Apple as they reside in different packages. I get the following error:
printName() has protected access in superClass.Fruit
Perfectly correct. But if I inherit from the class superClass as follows I do not get any error!
package food;
import superClass.*;
public class Apple extends Fruit {
public static void main(String[] args) {
int i, j;
for(i = 0; i < 5; i++) {
for(j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
printName(); // Call inherited member - NO ERROR, expected
Fruit f = new Fruit();
f.printName(); // Call instantiated member - NO ERROR, WHAT????
}
}
Why is it allowing me to access the protected member of another class in a different package by reference? This is supposed to be an illegal access, is it not?
I am confused! Someone please help.
The code was compiled using Java 1.6.0_18.