inheritance java syntax code example

Example 1: Inheritance in java

// Multiple inheritance in java
interface M
{
   public void helloWorld();
}
interface N
{
   public void helloWorld();
}
// implementing interfaces
public class MultipleInheritanceExample implements M, N
{
   public void helloWorld()
   {
      System.out.println("helloWorld() method");
   }
   public static void main(String[] args) 
   {
      MultipleInheritanceExample obj = new MultipleInheritanceExample();
      obj.helloWorld();
   }
}

Example 2: how to make one java class inherit from another

public class Bicycle {
        
    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;
        
    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
        
    // the Bicycle class has four methods
    public void setCadence(int newValue) {
        cadence = newValue;
    }
        
    public void setGear(int newValue) {
        gear = newValue;
    }
        
    public void applyBrake(int decrement) {
        speed -= decrement;
    }
        
    public void speedUp(int increment) {
        speed += increment;
    }
        
}

Tags:

Java Example