Java-Package with Multiple Public Classes

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 :

1) Define the class and make it public.
2) Place the package statement before the class definition.
3) Store this as MyClass2.java file under directory mypack.
4) Compile MyClass2.java file. This will create a MyClass2.class.

 

Program

502

Package Source

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();
    }
}

Leave a Comment