An Interface Example


Let’s consider the example of vehicles like bicycle, car, bike, etc. They have common functionalities. So we make an interface and put all these common functionalities. And let Bicylce, Bike, Car, etc. implement all these functionalities in their own classes in their own way.

GFG.java (a real-world interface example)
public class GFG {
  public static void main( String[ ] args ) {
    // Creating an instance of Bicycle doing some operations
    Bicycle bicycle = new Bicycle( );
    bicycle.changeGear ( Integer.parseInt( args[0] ) );
    bicycle.speedUp    ( Integer.parseInt( args[1] ) );
    bicycle.applyBrakes( Integer.parseInt( args[2] ) );
    bicycle.printStates( );

    // Creating an instance of bike
    Bike bike = new Bike( );
    bike.changeGear ( Integer.parseInt( args[3] ) );
    bike.speedUp    ( Integer.parseInt( args[4] ) );
    bike.applyBrakes( Integer.parseInt( args[5] ) );
    bike.printStates( );
  }
}

interface Vehicle { 
  // All are abstract methods. 
  void changeGear ( int a ); 
  void speedUp    ( int a ); 
  void applyBrakes( int a ); 
} 

class Bicycle implements Vehicle { 
  int speed;      // Default value is 0.
  int gear; 
	
  // to change gear 
  @Override
  public void changeGear( int newGear ) { gear = newGear; } 
	
  // to increase speed 
  @Override
  public void speedUp( int increment ) { speed = speed + increment; } 
	
  // to decrease speed 
  @Override
  public void applyBrakes( int decrement ) { speed = speed - decrement; } 
	
  public void printStates( ) { 
    System.out.print( speed + "|" + gear ); 
  } 
} 

class Bike implements Vehicle { 
  int speed; 
  int gear; 

  // to change gear 
  @Override
  public void changeGear( int newGear ) { gear = newGear; } 
	
  // to increase speed 
  @Override
  public void speedUp( int increment ) { speed = speed + increment; } 
	
  // to decrease speed 
  @Override
  public void applyBrakes( int decrement ) { speed = speed - decrement; } 
	
  public void printStates( ) { 
    System.out.print( "|" + speed + "|" + gear ); 
  }
}
shell> java GFG              

Output:           Result:




      All of us have been waiting for you for two hours –    
      but better late than never (never too late).