Search code examples
javainheritancemethodsgetter-setter

Best Practices for Implementing Setters/Getters in Subclasses?


If I have a superclass that must retain some functionality, thus requiring setters/getters (I realize this isn't ideal, but that's beside the point), when I implement a subclass, should I include a call to the superclass' setters/getters in the subclass even though I can technically invoke them without writing the code again?

I've posted an example of what I mean below.

class Parent {

   private int x;

   public void myMethod() {
      // Code here.
   }

   public void setX(int y) {
       x = y;
   }

   public int getX() {
       return x;
   }


}

class Child extends Parent {

   @Override 
   public void myMethod() {
      super.myMethod();
      // Different code here.
   }

   // Are the inclusions below really necessary? 
   public void setX(int y) {
       super.setX(y);
   }

   public int getX() {
       super.getX();
   }
}

Solution

  • Overriding methods to only call their super version is what you get by default without overriding!

    In other words:

    @Override
    void foo() { super.foo(); }
    

    results absolutely the same as behavior as ... not overriding that method at all.

    So, to the contrary: you should consider making those getters and setters final to prevent subclasses from overriding them! And for the record: when overriding methods, you always want to put the @Override annotation on those methods (so the compiler can tell you when you only think you are overriding a method).