java如何添加子类
在Java中添加子类
Java中通过继承机制实现子类的创建,子类继承父类的属性和方法,同时可以扩展或重写父类的功能。以下是具体实现步骤:
定义父类
父类是被继承的基类,需明确其属性和方法。例如:
public class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating.");
}
}
使用extends关键字创建子类
子类通过extends继承父类,语法为class SubClass extends SuperClass。例如:
public class Dog extends Animal {
public Dog(String name) {
super(name); // 调用父类构造方法
}
// 扩展子类特有方法
public void bark() {
System.out.println("Woof!");
}
}
调用父类构造方法
子类构造方法中需通过super()调用父类构造方法,且必须放在子类构造方法的第一行。例如:
public Dog(String name) {
super(name); // 必须优先调用
}
方法重写(Override)
子类可重写父类方法以实现多态。使用@Override注解明确标识:
@Override
public void eat() {
System.out.println("Dog is eating with enthusiasm.");
}
访问父类成员
通过super关键字访问父类的属性和方法:

public void showInfo() {
super.eat(); // 调用父类方法
}
注意事项
- Java仅支持单继承,一个子类只能有一个直接父类。
- 父类中
private成员对子类不可见,需通过protected或public方法访问。 - 若父类有无参构造方法,子类可不显式调用
super(),编译器会自动添加。
完整示例
// 父类
class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public void display() {
System.out.println("Brand: " + brand);
}
}
// 子类
class Car extends Vehicle {
private int year;
public Car(String brand, int year) {
super(brand);
this.year = year;
}
@Override
public void display() {
super.display();
System.out.println("Year: " + year);
}
}
// 使用
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2023);
myCar.display();
}
}






