Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Java: Packages - Defining

JavaFAQ Home » Java Notes by Fred Swartz Go to all tips in Java Notes by Fred Swartz


Bookmark and Share Multiple classes of larger programs are usually grouped together into a package. Packages correspond to directories in the file system, and may be nested just as directories are nested.

Reasons for using packages

  • To allow classes to be combined in a single ".jar" file.
  • To control the namespace.
  • To limit the scope of names.

Package declarations

Each file must have a package declaration which precedes all non-comment code. The package name must be the same as the enclosing directory. For example, here are two files in the packagetest directory.
package packagetest;
class ClassA {
    public static void main(String[] args) {
        ClassB.greet();
    }
}
and
package packagetest;
class ClassB {
    static void greet() {
        System.out.println("Hi");
    }
}
Note that these source files must be named ClassA.java and ClassB.java (case matters) and they must be in a directory named packagetest.

Compiling and running packages from a command line

To compile the above example, you must be outside the packagetest directory. To compile the classes:
   javac packagetest/ClassB.java
   javac packagetest/ClassA.java
To run the main program in ClassA.
   java packagetest.ClassA
or
   java packagetest/ClassA

In windows the "/" can be replaced by the "" in the javac command, but not in the java command. Generally use a forward slash ("/") because it is used more commonly than the backslash in other places as well.


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy