1. 定义 Person 类
public class Person {
    private String name;
    private int age;
    private String gender;
    
    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    
    public void eat() {
        System.out.println('吃饭');
    }
    
    public void show() {
        System.out.println('姓名:' + name + ',年龄:' + age + ',性别:' + gender);
    }
}
  1. 定义 Student 类
public class Student extends Person {
    private String studentId;
    private int score;
    
    public Student(String name, int age, String gender, String studentId, int score) {
        super(name, age, gender);
        this.studentId = studentId;
        this.score = score;
    }
    
    public void eat() {
        System.out.println('炒菜,吃米饭');
    }
    
    public void show() {
        super.show();
        System.out.println('学号:' + studentId + ',成绩:' + score);
    }
}
  1. 定义 Worker 类
public class Worker extends Person {
    private String workerId;
    private double salary;
    
    public Worker(String name, int age, String gender, String workerId, double salary) {
        super(name, age, gender);
        this.workerId = workerId;
        this.salary = salary;
    }
    
    public void eat() {
        System.out.println('炖菜,吃馒头');
    }
    
    public void show() {
        super.show();
        System.out.println('工号:' + workerId + ',薪资:' + salary);
    }
}
  1. 测试类
public class Test {
    public static void main(String[] args) {
        Student student = new Student('小明', 17, '男', 'NO13', 82);
        student.eat();
        student.show();
        
        Worker worker = new Worker('老明', 40, '男', 'GH34', 5800);
        worker.eat();
        worker.show();
    }
}
Java 继承案例:人类、学生和工人

原文地址: https://www.cveoy.top/t/topic/op8o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录