Search code examples
javaoopinheritanceencapsulation

Attribute should not be changed after creation


Given the question - "All game objects provide the ability for external code to obtain their size. However, they do not provide the ability to have their size changed once it is created."

If I have a parent class with private fields such as this GameObject class:

public abstract class GameObject {
     private int size;

     public void setSize(int size) {
          this.size = size;
     }
}

and a children classes such as

public class Dinosaur extends GameObject {
     public Dinosaur() {
           this.setSize(100);
     }
}

public class Jeep extends GameObject {
     public Jeep() {
          this.setSize(10);
     }
 }      

How do I ensure that the size is not changed after the object is created? I am confused because if I make the setter method for size private then I cannot set the size for each GameObject individually upon creation.

EDIT: Added second child class for clarity.


Solution

  • If you need to make the size variable unchangeable then you should use final modifier. There are 2 ways to set the value for this kind of variables: 1) constructor 2) inline. As long as you would like to have an option to set your custom value in the client code for each object, you should use constructor:

    public abstract class GameObject {
    
         private final int size;
    
         public GameObject(int size) {
             this.size = size;
         }
    }
    
    public Dinosaur extends GameObject {
    
       pubilc Dinosaur(int size){
           super(size);
       }
    }
    

    There is no need in setter method in that case.