Access Modifiers for Methods and Attributes


The following modifiers are used for attributes, methods, and constructors. The private and protected modifiers will be discussed when the inheritance is covered.

Modifier Description
public The code is accessible by any other class.
private The code is only accessible within the declared class.
default or nothing The code is only accessible by classes in the same package. This is used when you do not specify a modifier.
protected The code is accessible in the same package and subclasses.

The static and public Methods
A method could have either static or public keyword or both. A static method means that it can be accessed without creating an object of the class, unlike public, which can only be accessed by objects. The example below demonstrates the differences between static and public methods:

MyClass.java (static and public keywords)
// Java program using the public and static keywords
public class MyClass {
  public static void main( String[ ] args ) {
    int x = 10;
    myStaticMethod( x );              // Call the static method.
    myPublicMethod( x );              // Call the public method.
    MyClass myObj = new MyClass( );   // Create an object of MyClass.
    myObj.myPublicMethod( x );        // Call the public method on the object.
  }
  // a member variable
  int x = 5;
  // a static method
  static void myStaticMethod( int x ) { System.out.print( x ); }
  // a public method
  public void myPublicMethod( int x ) { System.out.print( x ); }
}
Output:           Result:




      “Don’t gain the world & lose your soul,    
      wisdom is better than silver or gold.”    
      ― Bob Marley