最多只能创建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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/AC_872767407/article/details/113538503
今日推荐