计算java创建的对象数量

我正在尝试计算创建的对象数,但它总是返回 1。


public class Drivertwo {


    public static void main(String[] args) {

        Employee newEmp = new Employee();

        Employee newEmp2 = new Employee();

        Calculate newcal = new Calculate();

        Clerk newclerk = new Clerk();


        float x;

        int y;


        newEmp.setEmp_no(2300);

        newEmp.setEmp_name("W.Shane");

        newEmp.setSalary(30000);

        newEmp.counter();


        newEmp2.setEmp_no(1300);

        newEmp2.setEmp_name("W.Shane");

        newEmp2.setSalary(50000);

        newEmp2.counter();


        newclerk.setEmp_name("Crishane");

        newclerk.setEmp_no(1301);

        newclerk.setGrade(2);

        newclerk.setSalary(45000);

        newclerk.counter();


        System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));

        System.out.println("Name is:" + newclerk.getEmp_name());

        System.out.println("Employee number is:" + newclerk.getEmp_no());

        System.out.println("Employee Grade is:" + newclerk.getGrade());

        System.out.println("No of objects:" + newEmp.numb);

这是我的课程,主要方法


public class Employee {

    private int salary;

    private int emp_no;

    private String emp_name;

    public int numb=0;


    public int getSalary() {

        return salary;

    }


    public int getEmp_no() {

        return emp_no;

    }


    public String getEmp_name() {

        return emp_name;

    }


    public void setSalary(int newSalary) {

        salary = newSalary;

    }


    public void setEmp_no(int newEmp_no) {

        emp_no = newEmp_no;

    }


    public void setEmp_name(String newEmp_name) {

        emp_name = newEmp_name;

    }



    }


    public int counter() {

        numb++;

        return numb;

这是我的 Employee 类


我试图在我的员工类中运行计数器作为启动器,但它总是返回 1。我知道我可以在主类中创建一个计数器,每次我创建一个新对象时,我都可以获得计数器,但我想自动将 numb 增加 1制作对象时。


HUH函数
浏览 301回答 3
3回答

潇潇雨雨

您需要使numb静态,以便该类的每个实例只有一个副本。事实上,每个Employee对象都有自己的numb.另外,与其创建一个增加计数器的方法,不如将它放在构造函数中:public Employee() {    numb++;    }

慕容森

numb是一个实例变量,这意味着每个Employee对象都有自己的numb,由 初始化0。如果您希望所有Employee实例共享相同的实例numb,您应该创建它static。

陪伴而非守候

// Java program Find Out the Number of Objects Created // of a Class class Test {     static int noOfObjects = 0;         // Instead of performing increment in the constructor instance block is preferred        //make this program generic. Because if you add the increment in the constructor         //it won't work for parameterized constructors    {         noOfObjects += 1;     }     // various types of constructors     public Test()     {     }     public Test(int n)     {     }     public Test(String s)     {     }     public static void main(String args[])     {         Test t1 = new Test();         Test t2 = new Test(5);         Test t3 = new Test("Rahul");         System.out.println(Test.noOfObjects);     } } 
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java