Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes How does one use 'package' ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How does one use Watch "How does one use New topic

How does one use 'package' ?

Dj Driver

Joined: Nov 11, 2011
Posts: 16
I am following the Head First Java book and I was reviewing the authors code for the Chapter 06 DotCom battleship game. There author has 2 java files and the corresponding .class files. They are in the chap06 directory. Each java file has 'package chap06;' as its first line of code. I am assuming they need this line of code as they need to be in the same directory?. The author has not covered the 'package' info yet. If the files are named and (as an example) how does one run them\it from the command line? Also, can I copy (using Notepad++) the files and have just a single .java file to compile and work with? And what is 'import helpers.GameHelper;' used for?
Jeff Verdegan

Joined: Jan 03, 2004
Posts: 6109

I'm sure if you google for something like java package tutorial there will be plenty of examples and explanations.

The basic idea is that packages are ways to group together related classes. Java requires that there be a correspondence between the directory path of a .class file relative to some classpath root and that class's package.

So, if MyClass is declared to be in package, and your classpath consists of C:/classes and C:/something.jar, then MyClass.class must either be at the path C:/classes/com/foo/MyClass.class or in C:/something.jar at com/foo/MyClass.class.
Brian Burress
Ranch Hand

Joined: Jun 30, 2003
Posts: 128
To embellish a little further, your question about how to execute from a command line you would need to have the root directory of the compiled class directory on your class path (the parent of the chap06 directorry) and would execute using chap06.<<classname>> where <<classname>> is first or second. Java will require the files to be in the proper directory as defined by package.

I am not looking at the source, you can work with a single file but you would likely have to refactor the code to account for not having the "second" class, etc. May not be a bad excerside from a beginning standpoint just to better understand how things fit together and relate.
I agree. Here's the link:
subject: How does one use 'package' ?
It's not a secret anymore!