Search code examples
javainheritancesubtype

Java Inheritance - setters only in subtypes


We have two Classes (one parent and a child). both uses private variables to store values, but the parent should NOT provide setters (x and y are given with the constructor and they are some sort of immutable). B should extend A with setters for x and y. Is there a common way to do so?

class A{
    private int x;
    private int y;

    A(int x, int y){
        this.x = x;
        this.y = y;
    }

}

class B extends A{

    public void setx(int x){
        this.x = x;
    }

    //same for y
}

Some thoughts

  • variables should be private
  • x and y of parent have to be immutable
  • B has to provide a public setter

Solution

  • If you want the variables to be immutable then it should be

    class B extends A{
    
        public B(int x, int y){
              super(x, y);
        }
    }
    

    At the moment your x and y variables in A are not immutable. To make them immutable then precede them with final

    This is the only way you can assign x and y as they are private. If you want setters then you will have to make the variables protected.

    Personally I am a big fan of immutability so would do this rather than setters - creating objects is usually quite cheap.