Advertisement
CR7CR7

InterfaceViechle

Oct 24th, 2023
529
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.03 KB | None | 0 0
  1.  
  2. import java.io.*;
  3.  
  4. interface Vehicle {
  5.    
  6.     // all are the abstract methods.
  7.     void changeGear(int a);
  8.     void speedUp(int a);
  9.     void applyBrakes(int a);
  10. }
  11.  
  12. class Bicycle implements Vehicle{
  13.    
  14.     int speed;
  15.     int gear;
  16.    
  17.      // to change gear
  18.     @Override
  19.     public void changeGear(int newGear){
  20.        
  21.         gear = newGear;
  22.     }
  23.    
  24.     // to increase speed
  25.     @Override
  26.     public void speedUp(int increment){
  27.        
  28.         speed = speed + increment;
  29.     }
  30.    
  31.     // to decrease speed
  32.     @Override
  33.     public void applyBrakes(int decrement){
  34.        
  35.         speed = speed - decrement;
  36.     }
  37.    
  38.     public void printStates() {
  39.          System.out.println("speed: " + speed
  40.               + " gear: " + gear);
  41.     }
  42. }
  43.  
  44. class Bike implements Vehicle {
  45.    
  46.     int speed;
  47.     int gear;
  48.    
  49.     // to change gear
  50.     @Override
  51.     public void changeGear(int newGear){
  52.        
  53.         gear = newGear;
  54.     }
  55.    
  56.     // to increase speed
  57.     @Override
  58.     public void speedUp(int increment){
  59.        
  60.         speed = speed + increment;
  61.     }
  62.    
  63.     // to decrease speed
  64.     @Override
  65.     public void applyBrakes(int decrement){
  66.        
  67.         speed = speed - decrement;
  68.     }
  69.    
  70.     public void printStates() {
  71.          System.out.println("speed: " + speed
  72.              + " gear: " + gear);
  73.     }
  74.    
  75. }
  76. class GFG {
  77.    
  78.     public static void main (String[] args) {
  79.    
  80.         // creating an inatance of Bicycle
  81.         // doing some operations
  82.         Bicycle bicycle = new Bicycle();
  83.         bicycle.changeGear(2);
  84.         bicycle.speedUp(3);
  85.         bicycle.applyBrakes(1);
  86.        
  87.         System.out.println("Bicycle present state :");
  88.         bicycle.printStates();
  89.        
  90.         // creating instance of the bike.
  91.         Bike bike = new Bike();
  92.         bike.changeGear(1);
  93.         bike.speedUp(4);
  94.         bike.applyBrakes(3);
  95.        
  96.         System.out.println("Bike present state :");
  97.         bike.printStates();
  98.     }
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement