Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Marcus Green - Exam 2 - Question 9 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Marcus Green - Exam 2 - Question 9" Watch "Marcus Green - Exam 2 - Question 9" New topic

Marcus Green - Exam 2 - Question 9

Jimmy Blakely
Ranch Hand

Joined: Jul 10, 2001
Posts: 57
Question 9)
What happens when you attempt to compile and run these two files in the same directory?
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
public class P2 extends P1{
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 is the equivalent of placing the file in a different directory to the file 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?

Matt Schwarz

Joined: Aug 16, 2001
Posts: 12
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.
Douglas Wolfinger
Ranch Hand

Joined: Aug 28, 2000
Posts: 57
I've been trying to see output from when I run P2.
I'm executing P1.afancymethod() from P2, but the print statement does not appear when I run it. I don't get output when I execute P2.afancymethod() either. Any suggestions?
Btw, I compile P1 with
'c:\jdk1.3\bin>javac -d c:\jdk1.3\bin' to create MyPackage.
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
// import MyPackage.*;
class P2 extends P1 {
public void afancymethod() {
public static void main(String args[]) {
P2 p2 = new P2();
P1 p1 = new P1();
I agree. Here's the link:
subject: Marcus Green - Exam 2 - Question 9
Similar Threads
Package visibility
Mock Exam Question
Cant think of one:-)
package directory