Package with Multiple Public Classes
A Java source file can have only one class declared as public, we cannot put two or more public classes together in a .java file. This is because of the restriction that the file name should be same as the name of the public class with .java extension. If we want to multiple classes under consideration are to be declared as public, we have to store them in separate source files and attach the package statement as the first statement in those source files.
If we want to add class to an existing package. For example the package mypack contains one public class by name MyClass. Suppose we want to add another public class MyClass2 to this package. This can be as follows :
Program
package mypack; public class MyClass2 { public void display() { System.out.println("MyClass2"); } }
Program Source
import mypack.MyClass2; public class Javaapp { public static void main(String[] args) { MyClass2 my2 = new MyClass2(); my2.display(); } }