aspose file tools*
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 Spring in Action this week in the Spring 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
Author

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?
//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?

Matt Schwarz
Greenhorn

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.
Matt
Douglas Wolfinger
Ranch Hand

Joined: Aug 28, 2000
Posts: 57
I've been trying to see output from P1.java 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 P1.java' to create MyPackage.
Thanks,
Doug
//File P1.java
package MyPackage;
class P1{
void afancymethod(){
System.out.println("What a fancy method");
}
}
// import MyPackage.*;
class P2 extends P1 {
public void afancymethod() {
System.out.println("P2.afancymethod()");
}
public static void main(String args[]) {
P2 p2 = new P2();
P1 p1 = new P1();
p1.afancymethod();
p2.afancymethod();
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Marcus Green - Exam 2 - Question 9