Logo
Section 1 / 12

理解继承

学习如何使用 extends 关键字创建可重用的类层次结构,使用 protected 修饰符控制访问权限,并使用 super 管理对象初始化。

导入

理解继承

学习如何使用 extends 关键字创建可重用的类层次结构,使用 protected 修饰符控制访问权限,并使用 super 管理对象初始化。

Table

Modifier类内访问子类内访问包内访问全局访问
private是否否否
protected是是是否
(无关键字)是仅在同一包内的子类是否
public是是是是
1class Vehicle { 2 // protected 允许子类直接访问此成员 3 protected String brand = "Generic Brand"; 4 5 public void honk() { 6 System.out.println("Tuut, tuut!"); 7 } 8} 9 10class Car extends Vehicle { 11 public int numberOfDoors = 4; 12 13 public void displayBrand() { 14 // 我们可以直接访问 'brand',因为它被声明为 protected 15 System.out.println("Vehicle Brand: " + brand); 16 } 17} 18 19public class Main { 20 public static void main(String[] args) { 21 var myCar = new Car(); 22 23 // 访问继承的方法 24 myCar.honk(); 25 26 // 通过子类方法访问继承的字段 27 myCar.displayBrand(); 28 29 // 访问子类特有的字段 30 System.out.println("Doors: " + myCar.numberOfDoors); 31 } 32}
1class Employee { 2 protected String name; 3 4 // 父类构造器需要一个名字 5 public Employee(String name) { 6 this.name = name; 7 System.out.println("Employee constructor called"); 8 } 9} 10 11class Manager extends Employee { 12 private int teamSize; 13 14 public Manager(String name, int teamSize) { 15 // 必须是第一行 16 super(name); 17 this.teamSize = teamSize; 18 System.out.println("Manager constructor called"); 19 } 20 21 public void displayInfo() { 22 System.out.println(name + " manages " + teamSize + " people."); 23 } 24} 25 26public class Main { 27 public static void main(String[] args) { 28 var mgr = new Manager("Alice", 5); 29 mgr.displayInfo(); 30 } 31}
1class Message { 2 public void print() { 3 System.out.println("Message from Parent"); 4 } 5} 6 7class Alert extends Message { 8 public void print() { 9 // 调用父类的 print 方法 10 super.print(); 11 System.out.println("Additional Alert Info"); 12 } 13} 14 15public class Main { 16 public static void main(String[] args) { 17 var alert = new Alert(); 18 alert.print(); 19 } 20}
1class Animal { 2 void eat() { 3 System.out.println("Eating..."); 4 } 5} 6 7class Mammal extends Animal { 8 void breathe() { 9 System.out.println("Breathing..."); 10 } 11} 12 13class Dog extends Mammal { 14 void bark() { 15 System.out.println("Woof!"); 16 } 17} 18 19public class Main { 20 public static void main(String[] args) { 21 var dog = new Dog(); 22 23 dog.bark(); // 定义在 Dog 中 24 dog.breathe(); // 从 Mammal 继承 25 dog.eat(); // 从 Animal 继承(祖父母) 26 } 27}

文件与数据输入输出

方法重写与多态性