类与对象(JAVA)

用一个学生自我介绍的例题,介绍类和对象的构造。。

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类的方法进行学生自我介绍,输出学生总人数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值