File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Compiling class with package 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 "Compiling class with package" Watch "Compiling class with package" New topic
Author

Compiling class with package

Astha Sharma
Ranch Hand

Joined: Oct 15, 2011
Posts: 245

This question is from K&B SCJP 6 book, page number 821, self test question number 3.

Default classpath is-

/foo

This is the directory structure-

foo
|
test
|
xcom
|--A.class
|--B.java

These are two files-

package xcom;
public class A{}

package xcom;
public class B extends A{}

Which allows B.java to compile?

A. Set current directory to xcom then invoke
javac B.java

B. Set current directory to xcom then invoke
javac -classpath . B.java

C. Set current directory to test then invoke
javac -classpath . xcom/B.java


Now my query is-

Why A nad B are wrong and C is correct?

Astha - OCPJP 6 (90%)
Khuzema Dharwala
Ranch Hand

Joined: Apr 26, 2010
Posts: 46

Hi Astha , always remeber when a class is defined in a package then its name is changed to "packagename.classname". To compile B compiler should able to trace A i.e the classpath should contain the route to get to A so coming back to your options question

1 option is incorrect because if you set the current directory as "xcom" then javac will not able to find A because it is looking for xcom.A not A in the current directory

2 option is incorrect because "javac B.java" and "javac -classpath . B.java" have the same meaning i.e if you don't include classpath option during compilation then by default the classpath will be "." (current directory)

3 option is correct because as default directory is now "test" and it contains subdirectory "xcom" hence compiler will not face any problem searching for xcom.A


OCJP 6
Astha Sharma
Ranch Hand

Joined: Oct 15, 2011
Posts: 245

Thanks a lot for the explanation Khuzema Dharwala.
Is there any way of compilation if I put class A without package and class B with package like this-

class A-

public class A{}

class B-

package xcom;
public class B extends A{}
Khuzema Dharwala
Ranch Hand

Joined: Apr 26, 2010
Posts: 46

Hi Astha,

You cannot refer to classes in the default package from classes in other packages. This has been the case since 2001. See the Release Notes for Java 1.4.

Classes in the default package cannot be imported by classes in packages. This is why you should not use the default package.

Thanks.
Astha Sharma
Ranch Hand

Joined: Oct 15, 2011
Posts: 245

Really helphul. Thanks Khuzema Dharwala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Compiling class with package