Marcus Green - Exam 2 - Question 9

Question 9) What happens when you attempt to compile and run these two files in the same directory? //File P1.java package MyPackage; class P1{ void afancymethod(){ System.out.println("What a fancy method"); } } //File P2.java public class P2 extends P1{ afancymethod(); } 1) Both compile and P2 outputs "What a fancy method" when run 2) Neither will compile 3) Both compile but P2 has an error at run time 4) P1 compiles cleanly but P2 has an error at compile time According to Green, the answer is 4 because: "The package statement in P1.java is the equivalent of placing the file in a different directory to the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that superclass P1 cannot be found." I agree its number 4, but.... Isn't afancymethod being called incorrectly by P2...or is there something I'm overlooking?

Since the class p1 is declared without any access modifiers, it is given the so-called "default" accessiblity, which is, it it only accessible to classes within the same package as the class in which it resides. P1 is in the MyPackage package, wheras P2 has no declared package (placing it, I believe, in the default package). Because of this default accessibility, no class outside of package MyPackage can subclass P1. This is why P2 will not compile. Matt