Example of Java inheritance: classes Car and Airplane inherit from Vehicle.

public class Vehicle {
    protected String model;
    protected int maxPassengers;
    protected double maxSpeed;  // mph

    public Vehicle(String m, int passengers, double speed) {
	model = m;
	maxPassengers = passengers;
	maxSpeed = speed;
    }

    // takes distance in miles, returns time in hours
    public double time(double distance) {
	return distance/maxSpeed;
    }
	

    public void print() {
	System.out.println("this is a " + model + ", it can carry " +
			   maxPassengers + " and can travel at " +
			   maxSpeed + " mph");
    }
}


public class Car extends Vehicle {
    private String transmissionType;

    public Car(String m, int passengers, double speed, String transmission) {
	super(m,passengers,speed);
	transmissionType = transmission;
    }

    public void print() {
	super.print();
	System.out.println("It has " + transmissionType + " transmission");
    }
}



public class Airplane extends Vehicle {
    private int maxAltitude;

    public Airplane(String m, int passengers, double speed, int altitude) {
	super(m,passengers,speed);
	maxAltitude = altitude;
    }

    public void print() {
	super.print();
	System.out.println("It's maximum altitude is " + maxAltitude);
    }
}



public class Test {
    public static void main(String [] args) {
	Car mycar = new Car("Dodge",4,80.0,"automatic");
	mycar.print();
	int distance = 5000;
	System.out.println("It will travel " + distance + " miles in " +
			   mycar.time(distance) + " hours");
	Airplane plane = new Airplane("Airbus",200,1000,30000);
	plane.print();
	System.out.println("It will travel " + distance + " miles in " +
			   plane.time(distance) + " hours");
    }
}


This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.