File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Packages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Packages" Watch "Packages" New topic


Hemant Gupt

Joined: May 12, 2008
Posts: 26
Source : Marcus Green Mock Exam Questions

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

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

Even though P2 is in the same directory as P1, because P1 was declared with the package statement it is not visible from P2
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

So, what's your question? The directory structure must match the package structure. If it doesn't, you'll get errors.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Kevin Smither
Ranch Hand

Joined: Oct 22, 2007
Posts: 30
first off, the class definition for P2 is wrong..where is the declaration for the method containing the call afancymethod? it's missing. P2 will not even compile because it's not Java syntax ;-)

second, the answer is not too clear, the reason it will not compile is because afancymethod is package private and hence not visible from P2 since P2 is in a different package.

Also, the compile directory has to be "MyPackage", if not you'll get errors.

Also, the classpath to the compiler has to be specified as one level below "MyPackage" otherwise you'll get more errors.

Another thing...the import statement is missing for P2
[ June 27, 2008: Message edited by: Kevin Smither ]
I agree. Here's the link:
subject: Packages
It's not a secret anymore!