The public Keyword for Classes


If a program contains multiple classes, at most one class can be assigned as public.

OnePublicClass.java (one public class)
// Java program using the public modifier  
public class OnePublicClass {
  public static void main( String[ ] args ) {
    int x = 10;
    DefaultClass myObj = new DefaultClass( x );
    myObj.display( myObj.x );
  }
}

class DefaultClass {
  // a member variable
  int x = 5;
  // a constructor
  public DefaultClass( int x ) { x = x; }
  // a member method
  public void display( int x ) { System.out.print( x ); }
}
Output:           Result:

The following program is the same as the above one, but with two public classes.

TwoPublicClass.java (two public classes)
// Java program using the public modifier  
public class TwoPublicClass {
  public static void main( String[ ] args ) {
    int x = 10;
    DefaultClass myObj = new DefaultClass( x );
    myObj.display( myObj.x );
  }
}

public class DefaultClass {
  // a member variable
  int x = 5;
  // a constructor
  public DefaultClass( int x ) { x = x; }
  // a member method
  public void display( int x ) { System.out.print( x ); }
}
Output:           Result: