创建学生父类human,子类Student。 1:human包含私有属性:姓名,性别;student包含私有属性学号,年级,学科 2:通过输入的方式从控制台输入这五个属性 3:将输入值赋值给student类实例 4:打印当前student类实例中的五个属性
时间: 2024-11-24 11:42:43 浏览: 11
Thpumaeu.zip_htpps://eu.puma.com_human_image_supervised learning
首先,我们创建一个`Human`父类,然后定义一个`Student`子类,按照您的要求:
```java
public class Human {
private String name;
private String gender;
// 构造函数
public Human(String name, String gender) {
this.name = name;
this.gender = gender;
}
// getter and setter methods (for simplicity, we'll omit them here)
}
public class Student extends Human {
private int studentID;
private int grade;
private String subject;
// 构造函数
public Student(String name, String gender, int studentID, int grade, String subject) {
super(name, gender); // Call the parent constructor
this.studentID = studentID;
this.grade = grade;
this.subject = subject;
}
// Getter and Setter methods for student-specific attributes (omitted for brevity)
@Override
public void printDetails() {
System.out.println("Name: " + getName());
System.out.println("Gender: " + getGender());
System.out.println("Student ID: " + getStudentID());
System.out.println("Grade: " + getGrade());
System.out.println("Subject: " + getSubject());
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter name:");
String name = scanner.nextLine();
System.out.println("Enter gender:");
String gender = scanner.nextLine();
System.out.println("Enter student ID:");
int studentID = scanner.nextInt();
scanner.nextLine(); // Consume newline left by nextInt()
System.out.println("Enter grade:");
int grade = scanner.nextInt();
scanner.nextLine(); // Consume newline left by nextInt()
System.out.println("Enter subject:");
String subject = scanner.nextLine();
Student student = new Student(name, gender, studentID, grade, subject);
student.printDetails();
}
}
```
在这个例子中,我们创建了`Human`和`Student`类,并为它们提供了必要的属性和构造函数。在`Main`类的`main`方法中,我们使用`Scanner`从控制台获取用户的输入并将其分配给`Student`实例的属性。最后,调用`printDetails()`方法打印所有属性。
阅读全文