Java 继承(子类和超类)
在 Java 中,可以从一个类继承属性和方法到另一个类。我们将“继承概念”分为两类:
子类(child): 从另一个类继承的类 超类(parent): 被继承的类
要从一个类继承,使用 extends 关键字。
示例:
1class Vehicle { 2 protected String brand = "Ford"; // Vehicle 属性 3 public void honk() { // Vehicle 方法 4 System.out.println("Tuut, tuut!"); 5 } 6} 7 8class Car extends Vehicle { 9 private String modelName = "Mustang"; // Car 属性 10 public static void main(String[] args) { 11 12 // 创建 myCar 对象 13 Car myCar = new Car(); 14 15 // 在 myCar 对象上调用 honk() 方法(来自 Vehicle 类) 16 myCar.honk(); 17 18 // 显示来自 Vehicle 类的 brand 属性的值和来自 Car 类的 modelName 的值 19 System.out.println(myCar.brand + " " + myCar.modelName); 20 } 21}
输出:
1Tuut, tuut! 2Ford Mustang
注意:
- 在上面的示例中,Vehicle 类是超类,Car 类是子类。
- Car 类继承了 Vehicle 类的 brand 属性和 honk() 方法。
- Car 类还可以添加自己的属性和方法,例如 modelName。
何时使用继承:
- 代码重用:在创建新类时,重用现有类的属性和方法。
- 代码的组织:将相关的类组织在一起,使其更容易理解和维护。
final 关键字:
如果不想让其他类从一个类继承,可以使用 final 关键字。
示例:
1final class Vehicle { 2 ... 3} 4 5class Car extends Vehicle { 6 ... 7}
输出:
1Main.java:9: error: cannot inherit from final Vehicle 2class Main extends Vehicle { 3 ^ 41 error
一些额外的说明:
- 一个类只能有一个超类。
- 子类可以访问超类的所有非私有成员(属性和方法)。
- 子类可以覆盖超类的方法,以提供不同的实现。
- 子类可以扩展超类的功能,添加新的属性和方法。
Java 多态
多态 意味着“多种形式”,它发生在我们有许多通过继承相互关联的类时。
继承允许我们从另一个类继承属性和方法。多态使用这些方法执行不同的任务。这使我们能够以不同的方式执行单个操作。
示例:
假设有一个名为 Animal 的超类,它具有一个名为 animalSound() 的方法。Animal 的子类可以是 Pig、Cat、Dog、Bird - 它们也有它们自己的实现动物声音的方法(猪发出哼哼声,猫发出喵喵声等):
1class Animal { 2 public void animalSound() { 3 System.out.println("The animal makes a sound"); 4 } 5} 6 7class Pig extends Animal { 8 public void animalSound() { 9 System.out.println("The pig says: wee wee"); 10 } 11} 12 13class Dog extends Animal { 14 public void animalSound() { 15 System.out.println("The dog says: bow wow"); 16 } 17}
现在我们可以创建 Pig 和 Dog 对象,并在它们两者上调用 animalSound() 方法:
1class Animal { 2 public void animalSound() { 3 System.out.println("The animal makes a sound"); 4 } 5} 6 7class Pig extends Animal { 8 public void animalSound() { 9 System.out.println("The pig says: wee wee"); 10 } 11} 12 13class Dog extends Animal { 14 public void animalSound() { 15 System.out.println("The dog says: bow wow"); 16 } 17} 18 19class Main { 20 public static void main(String[] args) { 21 Animal myAnimal = new Animal(); // 创建 Animal 对象 22 Animal myPig = new Pig(); // 创建 Pig 对象 23 Animal myDog = new Dog(); // 创建 Dog 对象 24 myAnimal.animalSound(); 25 myPig.animalSound(); 26 myDog.animalSound(); 27 } 28}
输出:
1The animal makes a sound 2The pig says: wee wee 3The dog says: bow wow
何时以及为何使用“继承”和“多态”?
- 代码重用: 在创建新类时,重用现有类的属性和方法。
- 代码的组织: 将相关的类组织在一起,使其更容易理解和维护。
- 灵活性: 允许代码以不同的方式执行,而无需更改代码本身。
多态的优点:
- 代码更简洁:只需要编写一次代码,就可以在不同的类上使用。
- 代码更易于维护:如果需要更改代码,只需更改一次,所有使用它的类都会自动更新。
- 代码更易于扩展:可以轻松添加新的类,而无需更改现有的代码。
一些额外的说明:
- 多态是面向对象编程的重要概念之一。
- 多态可以使代码更简洁、更易于维护和扩展。
- 抽象类和接口是实现多态的重要工具。
一些额外的思考:
- 您可以想象其他可以利用多态的示例吗?
- 多态在现实世界中有哪些应用?
最后
为了方便其他设备和平台的小伙伴观看往期文章:
微信公众号搜索:Let us Coding,关注后即可获取最新文章推送
看完如果觉得有帮助,欢迎 点赞、收藏、关注
