Java inheritance examples

Example 1: Inheritance in java

// single inheritance example
import java.util.*;
class Animal
{
   void eat()
   {
      System.out.println("Animal is eating.");
   }
}
class Lion extends Animal
{
   void roar()
   {
      System.out.println("lion is roaring.");
   }
   public static void main(String[] args)
   {
      Lion obj = new Lion();
      obj.eat();
      obj.roar();
   }
}

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;
    }
        
}

Example 3: Inheritance in Java

Java Inheritance (Subclass and Superclass)
In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories:

subclass (child) - the class that inherits from another class
superclass (parent) - the class being inherited from
To inherit from a class, use the extends keyword.

Tags:

Java Example