用Java编写代码:父类:学生类Student 属性:姓名、性别、学号等 构造函数(2个) 方法 从键盘输入该同学的信息 输出该学生信息(格式: 学号:** 姓名:** 性别:**等)
时间: 2024-06-25 11:00:47 浏览: 14
在Java中,你可以创建一个名为`Student`的抽象父类,包含基本的学生属性和一些方法。这里是一个简单的示例:
```java
// 定义父类 Student
public abstract class Student {
// 属性
private String name;
private String gender;
private int studentID;
// 构造函数(两个版本,一个无参构造用于子类)
public Student() {
this(null, null, 0);
}
protected Student(String name, String gender, int studentID) {
this.name = name;
this.gender = gender;
this.studentID = studentID;
}
// 输入学生信息的方法
public void inputStudentInfo() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学生的姓名:");
name = scanner.nextLine();
System.out.println("请输入学生的性别:");
gender = scanner.nextLine();
System.out.println("请输入学生的学号:");
studentID = scanner.nextInt();
scanner.close();
}
// 输出学生信息的方法
public void displayStudentInfo() {
System.out.printf("学号:%d 姓名:%s 性别:%s", studentID, name, gender);
}
// 省略的纯虚函数,如果需要可以添加
// public abstract void abstractMethod(); // 如果你打算为子类定义具体行为
// 父类的析构函数通常不需要显式声明为虚析构函数,因为Java自动处理
}
```
为了演示如何使用这个父类,你需要创建一个继承自`Student`的子类并实例化它。例如:
```java
public class RegularStudent extends Student {
public static void main(String[] args) {
RegularStudent student = new RegularStudent();
student.inputStudentInfo();
student.displayStudentInfo();
}
}
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)