写一个类 Student,包含姓名、年龄、学号、性别四个属性,并实现以下方法: 构造方法,传入以上四个参数并初始化对象。 toString(),返回该学生的信息字符串。
时间: 2023-11-27 18:54:50 浏览: 101
好的,以下是类 Student 的实现代码:
```java
public class Student {
private String name;
private int age;
private String studentID;
private String gender;
public Student(String name, int age, String studentID, String gender) {
this.name = name;
this.age = age;
this.studentID = studentID;
this.gender = gender;
}
@Override
public String toString() {
return "姓名:" + this.name + ",年龄:" + this.age + ",学号:" + this.studentID + ",性别:" + this.gender;
}
}
```
以上代码中,我们定义了一个名为 Student 的类,包含了四个属性:姓名、年龄、学号和性别。我们还实现了一个构造方法,用于初始化对象,以及一个 toString() 方法,用于返回该学生的信息字符串。
使用该类的示例代码如下:
```java
public class Main {
public static void main(String[] args) {
Student s = new Student("张三", 20, "20210001", "男");
System.out.println(s.toString());
}
}
```
以上代码中,我们创建了一个名为 s 的 Student 对象,并传入了相应的参数。然后我们调用了 toString() 方法,输出了该学生的信息字符串。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)