java继承学生成绩
时间: 2024-06-15 07:07:56 浏览: 17
Java中的继承是面向对象编程的重要概念之一,它允许一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法。在继承关系中,子类可以重用父类的代码,并且可以添加自己的特定功能。
在Java中,可以通过使用关键字`extends`来实现继承。子类可以继承父类的非私有属性和方法,并且可以通过重写父类的方法来实现自己的逻辑。
下面是一个示例代码,展示了Java中继承的基本用法:
```java
// 定义父类
class Student {
private String name;
private int age;
private int score;
// 构造方法
public Student(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
// 其他方法
public void displayInfo() {
System.out.println("姓名:" + name);
System.out.println("年龄:" + age);
System.out.println("成绩:" + score);
}
}
// 定义子类
class HighSchoolStudent extends Student {
private String schoolName;
// 构造方法
public HighSchoolStudent(String name, int age, int score, String schoolName) {
super(name, age, score);
this.schoolName = schoolName;
}
// getter和setter方法
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
// 重写父类的方法
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("学校:" + schoolName);
}
}
// 测试代码
public class Main {
public static void main(String[] args) {
HighSchoolStudent student = new HighSchoolStudent("张三", 16, 90, "高中一班");
student.displayInfo();
}
}
```
在上面的示例中,`Student`类是父类,`HighSchoolStudent`类是子类。子类`HighSchoolStudent`继承了父类`Student`的属性和方法,并且通过重写`displayInfo()`方法添加了自己的逻辑。在测试代码中,创建了一个`HighSchoolStudent`对象,并调用了`displayInfo()`方法来显示学生的信息。