Java 继续(子类和超类)
在 Java 中,可以从一个类继续属性和方法到另一个类。我们将“继续概念”分为两类:
子类(child): 从另一个类继续的类
超类(parent): 被继续的类
要从一个类继续,使用 extends 关键字。
示例:- class Vehicle {
- protected String brand = "Ford"; // Vehicle 属性
- public void honk() { // Vehicle 方法
- System.out.println("Tuut, tuut!");
- }
- }
- class Car extends Vehicle {
- private String modelName = "Mustang"; // Car 属性
- public static void main(String[] args) {
- // 创建 myCar 对象
- Car myCar = new Car();
- // 在 myCar 对象上调用 honk() 方法(来自 Vehicle 类)
- myCar.honk();
- // 显示来自 Vehicle 类的 brand 属性的值和来自 Car 类的 modelName 的值
- System.out.println(myCar.brand + " " + myCar.modelName);
- }
- }
复制代码 输出:留意:
- 在上面的示例中,Vehicle 类是超类,Car 类是子类。
- Car 类继续了 Vehicle 类的 brand 属性和 honk() 方法。
- Car 类还可以添加自己的属性和方法,例如 modelName。
何时使用继续:
- 代码重用:在创建新类时,重用现有类的属性和方法。
- 代码的组织:将相干的类组织在一起,使其更容易理解和维护。
final 关键字:
如果不想让其他类从一个类继续,可以使用 final 关键字。
示例:- final class Vehicle {
- ...
- }
- class Car extends Vehicle {
- ...
- }
复制代码 输出:- Main.java:9: error: cannot inherit from final Vehicle
- class Main extends Vehicle {
- ^
- 1 error
复制代码 一些额外的说明:
- 一个类只能有一个超类。
- 子类可以访问超类的全部非私有成员(属性和方法)。
- 子类可以覆盖超类的方法,以提供不同的实现。
- 子类可以扩展超类的功能,添加新的属性和方法。
Java 多态
多态 意味着“多种形式”,它发生在我们有许多通过继续相互关联的类时。
继续答应我们从另一个类继续属性和方法。多态使用这些方法执行不同的任务。这使我们能够以不同的方式执行单个操作。
示例:
假设有一个名为 Animal 的超类,它具有一个名为 animalSound() 的方法。Animal 的子类可以是 Pig、Cat、Dog、Bird - 它们也有它们自己的实现动物声音的方法(猪发出哼哼声,猫发出喵喵声等):- class Animal {
- public void animalSound() {
- System.out.println("The animal makes a sound");
- }
- }
- class Pig extends Animal {
- public void animalSound() {
- System.out.println("The pig says: wee wee");
- }
- }
- class Dog extends Animal {
- public void animalSound() {
- System.out.println("The dog says: bow wow");
- }
- }
复制代码 现在我们可以创建 Pig 和 Dog 对象,并在它们两者上调用 animalSound() 方法:- class Animal {
- public void animalSound() {
- System.out.println("The animal makes a sound");
- }
- }
- class Pig extends Animal {
- public void animalSound() {
- System.out.println("The pig says: wee wee");
- }
- }
- class Dog extends Animal {
- public void animalSound() {
- System.out.println("The dog says: bow wow");
- }
- }class Main { public static void main(String[] args) { Animal myAnimal = new Animal(); // 创建 Animal 对象 Animal myPig = new Pig(); // 创建 Pig 对象 Animal myDog = new Dog(); // 创建 Dog 对象 myAnimal.animalSound(); myPig.animalSound(); myDog.animalSound(); }}
复制代码 输出:- The animal makes a sound
- The pig says: wee wee
- The dog says: bow wow
复制代码 何时以及为何使用“继续”和“多态”?
- 代码重用: 在创建新类时,重用现有类的属性和方法。
- 代码的组织: 将相干的类组织在一起,使其更容易理解和维护。
- 灵活性: 答应代码以不同的方式执行,而无需更改代码本身。
多态的优点:
- 代码更简洁:只需要编写一次代码,就可以在不同的类上使用。
- 代码更易于维护:如果需要更改代码,只需更改一次,全部使用它的类都会自动更新。
- 代码更易于扩展:可以轻松添加新的类,而无需更改现有的代码。
一些额外的说明:
- 多态是面向对象编程的紧张概念之一。
- 多态可以使代码更简洁、更易于维护和扩展。
- 抽象类和接口是实现多态的紧张工具。
一些额外的思考:
- 您可以想象其他可以使用多态的示例吗?
- 多态在现实世界中有哪些应用?
末了
为了方便其他设备和平台的小同伴观看往期文章:
微信公众号搜索:Let us Coding,关注后即可获取最新文章推送
看完如果觉得有帮助,欢迎 点赞、收藏、关注
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |