用一个学生自我介绍的例题,介绍类和对象的构造。。
public class Student {
// 定义姓名,年龄和编号,3个字段。
private final String name;
private final int age;
private final int id;
// 定义2个静态字段
private static int studentCount = 0; // 统计学生总数
private static int nextId = 1000; // 下一个学生编号
public Student(String name, int age) {
this.name = name;
this.age = age;
this.id = nextId++; // 每次创建学生时,编号自动递增,且只能赋值一次
studentCount++; // 增加学生总数
}
// 输出学生信息的方法
public void introduce() {
System.out.printf("大家好,我是编号%d的%s,今年%d岁!我会好好学习,成为人生赢家!\n", id, name, age);
}
// 静态方法,返回学生总数
public static int getStudentCount() {
return studentCount;
}
}
首先创建一个Student类,在里面创建字段,构造器和方法,便于其他类调用。
public class StudentTest {
public static void main(String[] args) {
// 创建3个学生对象
Student s1 = new Student("张三", 20);
Student s2 = new Student("李四", 21);
Student s3 = new Student("王五", 19);
// 学生自我介绍
s1.introduce();
s2.introduce();
s3.introduce();
System.out.println("总学生数: " + Student.getStudentCount());
}
}
最后通过用于测试构造器的StudentTest类,构造3个学生对象,并引用Student类的方法进行学生自我介绍,输出学生总人数。