java设计一个学生类属性有姓名年龄学历,由student派生出本科生和研究生(继承关系),本科生增加属性专业,研究生增加研究方向属性,在测试类中测试输出每个类的实例的属性信息
时间: 2024-02-25 22:51:56 浏览: 29
好的,以下是Java代码实现:
```
// 学生类
class Student {
String name;
int age;
String education;
public Student(String name, int age, String education) {
this.name = name;
this.age = age;
this.education = education;
}
@Override
public String toString() {
return "姓名:" + name + ",年龄:" + age + ",学历:" + education;
}
}
// 本科生类
class Undergraduate extends Student {
String major;
public Undergraduate(String name, int age, String education, String major) {
super(name, age, education);
this.major = major;
}
@Override
public String toString() {
return super.toString() + ",专业:" + major;
}
}
// 研究生类
class Graduate extends Student {
String researchDirection;
public Graduate(String name, int age, String education, String researchDirection) {
super(name, age, education);
this.researchDirection = researchDirection;
}
@Override
public String toString() {
return super.toString() + ",研究方向:" + researchDirection;
}
}
// 测试类
public class Test {
public static void main(String[] args) {
Student s1 = new Student("张三", 20, "本科");
System.out.println(s1);
Undergraduate s2 = new Undergraduate("李四", 21, "本科", "计算机科学与技术");
System.out.println(s2);
Graduate s3 = new Graduate("王五", 25, "硕士", "人工智能");
System.out.println(s3);
}
}
```
输出结果:
```
姓名:张三,年龄:20,学历:本科
姓名:李四,年龄:21,学历:本科,专业:计算机科学与技术
姓名:王五,年龄:25,学历:硕士,研究方向:人工智能
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)