Wednesday, 19 August 2009

Java Certification Question 0069

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



Answer 4) P1 compiles cleanly but P2 has an error at compile time

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.

No comments: