Compiling Java Packages and Subpackages from the Command Line

The packaging system in Java can be tricky for the beginner to navigate. Follow the steps below to create, compile, and run a test program that creates a Java program whose classes belong to a root package and a subpackage.

1. In any convenient location, create a new directory named “PackageAndSubpackageTest”.

2. In the newly created PackageAndSubpackageTest directory, create a subdirectory named “RootPackage”.

3. In the newly created RootPackage directory, create a subdirectory named “Subpackage”.

4. Still in the RootPackageDirectory, create a new text file named PackageAndSubpackageTest.java, containing the following text:

package RootPackage;

import RootPackage.Subpackage.*;

public class PackageAndSubpackageTest
{
	public static void main(String[] args)
	{
		ClassInSubpackage instance = new ClassInSubpackage();
	    String messageFromSubpackage = instance.messageGet();
    	System.out.println(messageFromSubpackage);

    	String messageFromRootPackage =
        	instance.messageGetFromClassInRootPackage();
    	System.out.println(messageFromRootPackage);
	}
}

5. Still in the RootPackage directory, create a new text file named ClassInRootPackage.html, containing the following text:

package RootPackage;

public class ClassInRootPackage
{
	public String messageGet()
	{
		return "This is coming from class in the root package!";
	}
}

6. In the Subpackage directory, create a new text file named ClassInSubpackage.html, containing the following text:

package RootPackage.Subpackage;

import RootPackage.*;

public class ClassInSubpackage
{
	public String messageGet()
	{
		return "This is coming from class in a subdirectory!";
	}

	public String messageGetFromClassInRootPackage()
	{
		ClassInRootPackage instance = new ClassInRootPackage();
		String message = instance.messageGet();
		return message;
	}
}

7. Open a command prompt in the top-level PackageAndSubpackageTest directory, and run the following command:

javac -sourcepath . RootPackage/PackageAndSubpackageTest.java

8. Still in the command prompt, and in the same top-level directory, run the following command:

java RootPackage/PackageAndSubpackageTest

9. Verify that the following text appears:

This is coming from class in a subdirectory!
This is coming from class in the root package!
Advertisement
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s