java统计一个类中创建对象的个数,并使对象id递增---static关键字的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/83873941

一、思路

主要处理的问题:统计一个类中创建的对象的个数
1、在类中设置一个static的int变量,每次创建一个对象时,count加1

staic int count=0;
Person(){++count;}

2、 同时要让对象的id递增,只需把count加1的结果赋给id即可。

id=++count;

3、 为了让count在类外面无法改变,我们使用private修饰。

private static int count=0;

二、代码

package com.keyword.test;

/**
 *实现: 给对象创建唯一的id,并记录创建的对象的总数
 */
public class ObjectCountStatic {
    public static void main(String[] args) {
        System.out.println("Person类中创建了"+Person.getCount()+"个对象");
        Person person1=new Person("小明",12);
        Person person2=new Person("小红",10);
        System.out.println(person1);
        System.out.println(person2);
        System.out.println("Person类中创建了"+Person.getCount()+"个对象");
    }
}
class Person{
    private static int count=0;   //存储创建对象的总数
    int id;
    String name;
    int age;
    public static int getCount(){
        return count;
    }
    Person(String name,int age){
        id=++count;
        this.name=name;
        this.age=age;
    }
    public String toString(){
        return"id:"+id+" name:"+name+" age:"+age;
    }
}

结果:
坚持比努力更重要

猜你喜欢

转载自blog.csdn.net/hju22/article/details/83873941