public class Car {
protected int numberOfWheels = 4;
protected int numberOfSeats = 4;
protected int length = 10;
protected int height = 4;
protected int enginePower = 500;
public void start() {
}
public void stop() {
}
public void gear() {
}
public void turn() {
}
public void brake() {
}
}This class models a real car (abstraction) which has 4 wheels and can carry up to 4 persons. It has basic behaviors of a standard car (encapsulation) such as start, stop, gear, turn and brake.This car can also carry a small amount of goods such as luggage and home stuffs. That’s good enough for households.However, if you open a consumer business, you definitely need a bigger car that is able to carry much more goods and carry fewer people. You may guess it: A truck.A truck is a car, except that it has bigger payload, stronger engine and fewer seats. In Java, we create the Truck class like this:public Truck extends Car {
}Here, the keyword extends is used to make a class inherits data and behaviors of another class. This is called Inheritance. The Truck class inherits all the characteristics and behaviors of a car.The truck is bigger and stronger than the car, thus it’s logical to reset relevant characteristics in the constructor:public Truck extends Car {
public Truck() {
numberOfWheels = 8;
numberOfSeats = 2;
enginePower = 1500;
length = 20;
height = 8;
}
}class FireTruck extends Truck {
public FireTruck() {
length = 28;
height = 12;
enginePower = 2000;
}
public void blowWater() {
}
}Here, as you can see, the FireTruck is bigger and stronger than a normal truck, and it has a special behavior: blowWater() to stop fire.The characteristics of the FireTruck are reset in its constructor, and the new behavior is implemented in a new method. A FireTruck is a Truck, which is a Car, so we can have the following relationship:Car -> Truck -> FireTruck
This is called inheritance tree which represents the parent-child relationship among classes.public class Person { }
public class Deisnger extends Person { }
public class Programmer extends Person { }
public class Architect extends Programmer { }public interface Wearable { }
public class Shirt implements Wearable { }
public class Glass implements Wearable { } public interface Collection { }
public interface List extends Collection { }
public interface Set extends Collection { }
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.