定义一个包含学号、姓名、年龄、成绩和手机号的学生类Student,并存放在包com.xhu下。然后在编写测试类TestStudent,在类中创建两个学生对象,并输出学生信息。
时间: 2024-11-03 15:14:42 浏览: 40
在Java中,你可以按照以下步骤定义一个`Student`类并创建一个`TestStudent`类来进行测试:
首先,我们定义`com.xhu.Student`类:
```java
package com.xhu;
public class Student {
private String studentId;
private String name;
private int age;
private double score;
private String phoneNumber;
// 构造函数
public Student(String studentId, String name, int age, double score, String phoneNumber) {
this.studentId = studentId;
this.name = name;
this.age = age;
this.score = score;
this.phoneNumber = phoneNumber;
}
// 获取和设置方法
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
// 重写toString方法,用于方便打印学生信息
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
```
接着,我们编写`com.xhu.TestStudent`类来测试`Student`类:
```java
package com.xhu;
import java.util.Scanner;
public class TestStudent {
public static void main(String[] args) {
// 创建第一个学生对象
Student student1 = new Student("001", "张三", 18, 93.5, "13812345678");
// 创建第二个学生对象
Student student2 = new Student("002", "李四", 20, 88.0, "13987654321");
// 输出学生信息
System.out.println("Student 1 Information:");
System.out.println(student1);
System.out.println("\nStudent 2 Information:");
System.out.println(student2);
}
}
```
在这个例子中,我们创建了两个`Student`对象,并分别设置了他们的属性值。然后通过`toString()`方法输出每个学生的详细信息。
阅读全文