M. R.
M. R.

Reputation: 23

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();
   }
}

Upvotes: 2

Views: 1431

Answers (4)

GhostCat
GhostCat

Reputation: 140641

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).

Upvotes: 2

Sondering Narcissist
Sondering Narcissist

Reputation: 419

Use superclass accessors if you need to access private fields from parent objects specifically. If you have different instance fields defined in the child class, you'd need separate getters to access those fields/variables.

Otherwise, just use the predefined super methods, which are inherited by all classes that extend the parent class.

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 192043

should I include a call to the superclass' setters/getters in the subclass

Firstly, if you want the child to have access to private int x, change private to protected.

The only reason I can think of when to return/set different data is when, for example, the subclass does some additional calculations upon y before setting x. Otherwise, if you just delegate to the super method, then that definition is unnecessary.

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

The whole point of inheritance is to NOT have to reimplement methods in a subclass if the superclass methods do what you need. You should override only if the subclass method needs to do something different/more.

Upvotes: 3

Related Questions