用Java 定义一个包含学号、姓名、年龄、成绩和手机号的学生类Student,并存放在包com.xhu下。然后在编写测试类TestStudent,在类中创建两个学生对象,并输出学生信息。
时间: 2024-11-20 08:41:06 浏览: 10
ORALCE 内置函数大全
3星 · 编辑精心推荐
在Java中,首先需要定义一个名为`Student`的类,该类将存储学生的相关信息并放入`com.xhu`包中。以下是简单的实现:
```java
// Student.java (位于com/xhu包下)
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; }
// 输出学生信息的方法
@Override
public String toString() {
return "Student{" +
"studentId='" + studentId + '\'' +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
```
接下来,我们会在`TestStudent`测试类中创建并使用这个学生类:
```java
// TestStudent.java
package com.xhu.test;
import com.xhu.Student;
public class TestStudent {
public static void main(String[] args) {
// 创建第一个学生对象
Student student1 = new Student("001", "张三", 20, 85.5, "1234567890");
// 创建第二个学生对象
Student student2 = new Student("002", "李四", 22, 90.0, "9876543210");
// 输出学生信息
System.out.println("学生1信息: " + student1);
System.out.println("学生2信息: " + student2);
}
}
```
运行`TestStudent`类会显示每个学生的信息。
阅读全文