Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); }
Now, let us implement the above interface in the same package animals −
package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } }
Now compile the java files as shown below −
$ javac -d . Animal.java $ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.
You can execute the class file within the package
$ java animals.MammalInt
and get the result as shown below.
Mammal eats Mammal travels