True or false: If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y. Correct answer is FALSE, but javac (1.4, 5, 6..) compiler successfully compiles classes of test program.
I'll be very thankful if you could provide me some hints why this is hapenning, why compiler produces no error? My first answer for the question was FALSE, but when I tried to check it, I found myself in strange situation being unable to understand what is wrong :) Please help me.
Program output: y.Child[1] calling doit() using reference to y.Child[2] protected method y.Child.doit() is called from class in package y y.Child[1] calling doit() using reference to y.Child[1] protected method y.Child.doit() is called from class in package y
Here is source code for test program.
public class InherintanceTest { public static void main(String[] args) { y.Child y1 = new y.Child(); y.Child y2 = new y.Child(); y1.callDoit(y2); y1.makeSelfCall(); } }
package y;
public class Child extends x.Base { private static int i; private int getint() { return ++i; } private int name; public Child() { name = getint(); } public void callDoit(Child obj) { System.out.println(toString() + " calling doit() using reference to " + obj); obj.doit(); // EXPECTING COMPILER ERROR, BUT NO ERROR PRESENTED } public void makeSelfCall() { callDoit(this); }
public String toString() { return getClass().getName() + "[" + name + "]"; } }
package x;
public class Base { protected void doit() { System.out.println("protected method " + getClass().getName() + ".doit() is called from class in " + getClass().getPackage()); } }