What are the alternatives to public fields?

前端 未结 12 2715
刺人心
刺人心 2021-02-19 15:05

I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being)

From what i have seen public fields a

12条回答
  •  太阳男子
    2021-02-19 15:36

    A shorter version of your methods...

    public void beDamaged(double damage) {
        health = Math.max(0, health-damage);
    }
    
    public void gainHealth(double gainedHp) {
        health = Math.min(maxHealth, health + gainedHp);
    }
    

    or even the following which can be called with +1 to gain, -1 to lose 1 hp.

    public void adjustHealth(double adjustHp) {
        health = Math.max(0, Math.min(maxHealth, health + adjustHp));
    }
    

提交回复
热议问题