The protected Keyword


When a method or a variable is marked as protected, it can be accessed from The main purpose of protected keyword is to have the method or variable can be inherited by subclasses.

Car.java (the protected keyword)
// Superclass
class Vehicle {
  protected int year;                // Vehicle attribute
  Vehicle( int y ) { year = y; }     // Vehicle constructor
  protected void honk( ) {           // Vehicle method
    System.out.print( "Honk! " );
  }
}

// Subclass
class Car extends Vehicle {
  public static String brand;        // Car attribute

  public static void main( String[ ] args ) {
    // Assign a brand value.
    brand = args[0];
    // Create a myCar object.
    Vehicle myCar = new Car( args[1] );
    // Call the honk( ) method (from the Vehicle class) on the myCar object.
    myCar.honk( );
    // Display the values of the brand & year attributes
    System.out.print( myCar.brand + " " + myCar.year );
  }

  // Constructor
  Car( String year ) { super( Integer.parseInt( year ) ); }
}
shell> java Car    

Output:           Result:




      I’ll call you back in an hour.    
      The speaker is almost finished, and I’m on deck (next).