There is a cat's weight, there is a maximum and minimum possible weight, when the cat goes beyond the allowable weight, the cat dies. How to freeze the variable "weight", i.e. so that the weight of the dead cat could not be changed?

I tried to use final, but in my opinion it only works when declaring a new variable. Or it was not necessary to write an if condition in the constructor, although when writing in a class, everything gets worse ...

public Cat() { weight = 1500.0 + 3000.0 * Math.random(); originWeight = weight; minWeight = 1000.0; maxWeight = 9000.0; count++; if(weight < minWeight || weight > maxWeight) { this.weight = final(); } } 

Hmm, what's wrong with a setter with a check? ru.wikipedia.org/wiki/Setter#Java

Something is already there. But I do not understand how to fix the weight?

 public String getStatus() { if(weight < minWeight) { count--; return "Dead"; } else if(weight > maxWeight) { count--; return "Exploded"; } else if(weight > originWeight) { return "Sleeping"; } else { return "Playing"; } } 

    2 answers 2

    As already mentioned in comments , you need to make a setter with a condition.

     class Cat { private int weight = 0; public Cat(int weight) { this.weight = weight; } public void setWeight(int weight) { // Если вес меньше 100 изменяем значение переменной иначе ничего не делаем // Если условие не выполнено можно выкинуть ошибку или еще что то сделать if (this.weight < 100){ this.weight = weight; } else { System.out.println("Кот слишком толстый"); } } public int getWeight() { return this.weight; } } 
       public class Cat { public static int count; private double weight; private boolean isDead; public Cat(double weight) { this.weight = weight; this.count++; if (weightKill()) { System.out.println('Dead before born'); } } public void setWeight(double weight) { if (this.isDead) { System.out.println('This cat is dead yet'); return; } this.weight = weight; if (weightKill()) { System.out.println('This diet is killing'); } } private boolean weightKill() { if (this.weight > 20.0 || this.weight < 1.0) { this.isDead = true; this.count--; } return this.isDead; } }