计算类中类的实例数

时间:2015-01-14 12:26:52

标签: java

我被要求在类StealthCruiser中构建方法“getAnnualMaintenanceCost”,用于计算某事物的总成本。 总成本的一个组成部分取决于为同一个类创建的实例数,如何计算数量?

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class StealthCruiser extends AbstractCompbatShip {

    static final int COST_BASIC = 2000;
    static final int COST_PER_UNIT1 = 1000;
    static final int COST_PER_UNIT2 = 100;

    private Weapon defaultWeapon;

    public StealthCruiser(String name, int commissionYear, float maximalSpeed, 
            Set<CrewMember> crewMembers, List<Weapon> weaponArray) {
        super(name, commissionYear, maximalSpeed, crewMembers, weaponArray);
    }

    public StealthCruiser(String name, int commissionYear, float maximalSpeed,
            Set<CrewMember> crewMembers) {
        super(name, commissionYear, maximalSpeed, crewMembers,
                Arrays.asList(new Weapon("Laser Cannons", 10 ,100)));
    }


    @Override
    public int getAnnualMaintenanceCost() {
        return COST_BASIC + 
               (int)(super.getMaximalSpeed() * COST_PER_UNIT1) +                                
               super.getWeaponsCost() +
               (COST_PER_UNIT2 * ...... //should be number of instances of that class;
    }

....

}

3 个答案:

答案 0 :(得分:3)

最简单的方法是在类中使用静态“instanceCount”成员并在构造函数中增加它。如果这是作业,这应该是一个足够好的解决方案。

答案 1 :(得分:2)

最简单的机制是在构造函数中有一个增量的静态变量:

class StealthCruiser {
    static int numberCruisers = 0;
    public StealthCruiser(...) {
        numberCruisers++;
    }
}

答案 2 :(得分:1)

你可以添加一个private static int instanceCounter变量,每次调用一个构造函数时它都会递增。

import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class StealthCruiser extends AbstractCompbatShip {

    static final int COST_BASIC = 2000;
    static final int COST_PER_UNIT1 = 1000;
    static final int COST_PER_UNIT2 = 100;

    private static final instanceCounter = 0;

    private Weapon defaultWeapon;

    public StealthCruiser(String name, int commissionYear, float maximalSpeed,
            Set<CrewMember> crewMembers, List<Weapon> weaponArray) {
        super(name, commissionYear, maximalSpeed, crewMembers, weaponArray);

        ++instanceCounter;
    }

    public StealthCruiser(String name, int commissionYear, float maximalSpeed,
            Set<CrewMember> crewMembers) {
        super(name, commissionYear, maximalSpeed, crewMembers,
                Arrays.asList(new Weapon("Laser Cannons", 10 ,100)));

        ++instanceCounter;
    }


    @Override
    public int getAnnualMaintenanceCost() {
        return COST_BASIC +
               (int)(super.getMaximalSpeed() * COST_PER_UNIT1) +
               super.getWeaponsCost() +
               (COST_PER_UNIT2 * instanceCounter);
    }

    ...
}