Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus Green - Exam 2 - Question 9

 
Jimmy Blakely
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic