java 如何继承类
继承的基本语法
在 Java 中,继承通过 extends 关键字实现。子类继承父类的非私有属性和方法。语法如下:
class ParentClass {
// 父类的属性和方法
}
class ChildClass extends ParentClass {
// 子类的属性和方法
}
继承的示例代码
以下是一个具体的继承示例:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // 继承自 Animal 类
dog.bark(); // Dog 类自身的方法
}
}
方法重写(Override)
子类可以重写父类的方法以提供特定实现。使用 @Override 注解表明方法重写:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Cat cat = new Cat();
cat.makeSound(); // 输出 "Cat meows"
}
}
继承中的构造方法
子类构造方法默认调用父类的无参构造方法。如需调用父类的有参构造方法,使用 super 关键字:
class Vehicle {
String type;
Vehicle(String type) {
this.type = type;
}
}
class Car extends Vehicle {
int wheels;
Car(String type, int wheels) {
super(type); // 调用父类构造方法
this.wheels = wheels;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car("Sedan", 4);
System.out.println(car.type + " has " + car.wheels + " wheels");
}
}
继承的限制
- Java 不支持多重继承,一个类只能继承一个父类。
- 父类的私有成员(
private)不能被继承。 final类不能被继承。
抽象类与继承
抽象类通过 abstract 关键字定义,可以包含抽象方法(无实现)。子类必须实现所有抽象方法:

abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
}
}






