掌握继承机制利用父类派生子类,定义人类(姓名,性别,年龄),定义学生类(新增学号,综合成绩),定义大学生类(专业特长),定义测试类
时间: 2024-10-12 14:16:54 浏览: 28
在面向对象编程中,继承是一种创建新类的方式,它允许我们从现有的类(也称为父类或超类)继承属性和方法。这里是一个简单的例子来解释如何利用继承机制:
首先,我们可以定义一个基础的人类类,包含一些通用属性如姓名、性别和年龄:
```java
public class Person {
private String name;
private String gender;
private int age;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
// getter and setter methods for properties...
}
```
接着,我们可以创建一个`Student`类,它是`Person`的子类,增加特定于学生的属性,比如学号和综合成绩:
```java
public class Student extends Person {
private String studentId;
private double overallGrade;
public Student(String name, String gender, int age, String studentId, double overallGrade) {
super(name, gender, age);
this.studentId = studentId;
this.overallGrade = overallGrade;
}
// getter and setter methods for studentId and overallGrade...
}
```
然后,为了进一步细化,我们可以创建一个更具体的`UniversityStudent`或`大学生`类(假设这个类名称未给出,我们暂且叫它`UniversityStudent`),它扩展了`Student`类并添加专业特长:
```java
public class UniversityStudent extends Student {
private String majorSpecialty;
public UniversityStudent(String name, String gender, int age, String studentId,
double overallGrade, String majorSpecialty) {
super(name, gender, age, studentId, overallGrade);
this.majorSpecialty = majorSpecialty;
}
// getter and setter method for majorSpecialty...
}
```
最后,可以有一个测试类`Test`来实例化和操作这些类:
```java
public class Test {
public static void main(String[] args) {
UniversityStudent student = new UniversityStudent("张三", "男", 20, "123456", 85.0, "计算机科学");
System.out.println("Name: " + student.getName());
System.out.println("Major Specialty: " + student.getMajorSpecialty());
// 更多的操作...
}
}
```
阅读全文