最多只能创建10个Student对象(静态成员变量、private构造方法)

定义一个Student类,并要求其他类在使用Student类的时候,最多只能创建10个Student类的对象

1、私有化构造方法
2、只能在内部创建,并返回该对象(通过Student类内部的方法)
需要一个计数器count指示当前类创建了多少次对象(count必须是类所有,全体对象共享)
public class Test {
    public static void main(String[] args) {
        //Student student = new Student();    //error
        for (int i = 0; i <= 10; i++) {
            Student.createNew();
        }
    }
}

class Student {
    //私有化构造方法(构造方法权限改为private)
    private Student() {
    }
	
	//只能在内部创建,并返回该对象
	//需要一个计数器count指示当前类创建了多少次对象(普通成员变量为对象所有,每创建一次就有一个新的,不可以)(核心要点:count必须是类所有,全体对象共享)
    //把创建Student对象的工作,交给一个专门的方法去做    if流程控制
    static int i = 1;
    public static Student createNew() {
    	//这个时候仍然可以创建对象
        if (i <= 10) {
            System.out.println("你的第" + i + "个Student对象");
            Student student = new Student();
            i++;
            return student;
        } else {
            System.out.println("创建对象失败,最多只能创建10个Student类的对象。");
            return null;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lacrimosa&L

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值