继承是面向对象的编程概念之一。这个概念允许类从其他类继承常用的状态和行为。继承是将常用状态和行为放入一个类并重用它的方法。
从其他类继承所有属性的类称为子类。而继承的类称为超类。您可以extends在类定义中使用关键字来继承其他类。
当您将final关键字应用于类声明时,您将使该类成为最终类,而其他类不能扩展最终类。
例如,下面有一个Truck类和一个Sedan从Car类派生的。
package org.nhooo.example.fundamental; public class CarDemo { public static void main(String[] args) { Car car = new Car(); car.setBrand("Honda"); System.out.println("Brand = " + car.getBrand()); // setBrand()和getBrand()继承自Car // 类。 Truck truck = new Truck(); truck.setBrand("Ford"); System.out.println("Brand = " + truck.getBrand()); truck.getLoadCapacity(); // setBrand(),getBrand()和setNumberOfSeat方法 // 是从Car类继承的。 Sedan sedan = new Sedan(); sedan.setBrand("Hyundai"); System.out.println("Brand = " + sedan.getBrand()); sedan.setNumberOfSeat(2); sedan.getGearType(); } }
在这里Car,,Truck和Sedan类的定义。
package org.nhooo.example.fundamental; public class Car { private String type; private String brand; private String model; private int numberOfSeat; public Car() { } public Car(String type, String brand, String model) { this.type = type; this.brand = brand; this.model = model; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public int getNumberOfSeat() { return numberOfSeat; } public void setNumberOfSeat(int numberOfSeat) { this.numberOfSeat = numberOfSeat; } public String getCarInfo() { return "Type: " + type + "; Brand: " + brand + "; Model: " + model; } }
package org.nhooo.example.fundamental; public class Truck extends Car { private int loadCapacity; public Truck() { } public Truck(String type, String brand, String model) { super(type, brand, model); } public int getLoadCapacity() { return loadCapacity; } public void setLoadCapacity(int loadCapacity) { this.loadCapacity = loadCapacity; } @Override public String getCarInfo() { return "Type: " + getType() + "; Brand: " + getBrand() + "; Model: " + getModel() + "; Load capacity: " + getLoadCapacity(); } }
package org.nhooo.example.fundamental; public class Sedan extends Car { private int gearType; public Sedan() { } public int getGearType() { return gearType; } public void setGearType(int gearType) { this.gearType = gearType; } }