Java 学生类和测试类示例 | 代码详解
以下是一个简单的 Java 学生类和测试类的示例,演示了如何创建类、属性、方法以及如何使用测试类实例化对象并调用方法。
学生类:
public class Student {
private String name;
private int age;
private String major;
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getMajor() {
return major;
}
}
测试类:
public class TestStudent {
public static void main(String[] args) {
Student student1 = new Student('Alice', 20, 'Computer Science');
Student student2 = new Student('Bob', 21, 'Business');
System.out.println(student1.getName() + ' is ' + student1.getAge() + ' years old and majors in ' + student1.getMajor());
System.out.println(student2.getName() + ' is ' + student2.getAge() + ' years old and majors in ' + student2.getMajor());
}
}
输出结果:
Alice is 20 years old and majors in Computer Science
Bob is 21 years old and majors in Business
原文地址: https://www.cveoy.top/t/topic/mizT 著作权归作者所有。请勿转载和采集!