6.2 继承与重写
继承(inheritance)允许一个类获得另一个类的字段和方法。它适合表达“是一种”的关系,例如 Food 是一种 Product,Drink 也是一种 Product。
继承
父类(parent class)保存共性,子类(subclass)补充差异。
正在加载交互实验...
java
class Product {
private String name;
private double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
String getName() {
return name;
}
double getPrice() {
return price;
}
}
class Food extends Product {
private int calories;
Food(String name, double price, int calories) {
super(name, price);
this.calories = calories;
}
int getCalories() {
return calories;
}
}
class Drink extends Product {
private String size;
Drink(String name, double price, String size) {
super(name, price);
this.size = size;
}
String getSize() {
return size;
}
}super(name, price) 会调用父类构造方法,先初始化产品共有的 name 和 price。
正在加载概念检查...
重写
当子类需要改变从父类继承来的行为时,可以重写(override)方法。最常见的例子是重写 toString()。
正在加载交互实验...
java
class Product {
private String name;
private double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return String.format("%s (%.2f元)", name, price);
}
}
class Food extends Product {
private int calories;
Food(String name, double price, int calories) {
super(name, price);
this.calories = calories;
}
@Override
public String toString() {
return String.format("食物:%s,%d 千卡", super.toString(), calories);
}
}
public class ProductDemo {
public static void main(String[] args) {
Food food = new Food("芝士汉堡", 35.8, 302);
System.out.println(food);
}
}运行结果:
text
食物:芝士汉堡 (35.80元),302 千卡子类的 toString() 可以调用 super.toString() 复用父类已经写好的字符串格式。
正在加载概念检查...
重写时复用父类逻辑
重写并不代表完全丢掉父类代码。很多时候,子类只想在父类结果前后补充信息,所以会在重写方法里调用 super。
java
@Override
public String toString() {
return String.format("食物:%s,%d 千卡", super.toString(), calories);
}正在加载概念检查...
正在加载本节练习...