javaj1.设计一个学生类Student,其属性有name(姓名),age(年龄)和degree(学位) 2.由Student类派生出本科生类Undergraduate和研究生类Graduate 3.Undergraduate类增加属性specialty(专业) 4.Graduate类增加属性direction(研究方向) 5.每个类都有show()方法,输出其属性信息
时间: 2023-06-02 18:06:51 浏览: 144
Sure, I'd love to answer your question about Java programming. Here's an implementation of the Student class and its derived classes:
```
public class Student {
protected String name;
protected int age;
protected String degree;
public Student(String name, int age, String degree) {
this.name = name;
this.age = age;
this.degree = degree;
}
public void show() {
System.out.printf("Name: %s\nAge: %d\nDegree: %s\n", name, age, degree);
}
}
public class Undergraduate extends Student {
private String specialty;
public Undergraduate(String name, int age, String degree, String specialty) {
super(name, age, degree);
this.specialty = specialty;
}
public void show() {
super.show();
System.out.printf("Specialty: %s\n", specialty);
}
}
public class Graduate extends Student {
private String direction;
public Graduate(String name, int age, String degree, String direction) {
super(name, age, degree);
this.direction = direction;
}
public void show() {
super.show();
System.out.printf("Direction: %s\n", direction);
}
}
```
Here's how you can use these classes to create instances and display their information:
```
public static void main(String[] args) {
Student s1 = new Student("John", 20, "Bachelor");
s1.show(); // Name: John\nAge: 20\nDegree: Bachelor
Student s2 = new Undergraduate("Alice", 19, "Bachelor", "Computer Science");
s2.show(); // Name: Alice\nAge: 19\nDegree: Bachelor\nSpecialty: Computer Science
Student s3 = new Graduate("Bob", 25, "Master", "Artificial Intelligence");
s3.show(); // Name: Bob\nAge: 25\nDegree: Master\nDirection: Artificial Intelligence
}
```
I hope this helps! Let me know if you have any more questions about Java programming.
阅读全文