0

Is there any advantage to storing a reference to a child instance field in the base class, as opposed to always calling an abstract getter when accessing it in the base class?

Suppose I have a base class like below:

 public abstract class BaseClass {
    abstract String getText();

    public void printText() {
       System.out.println(getText());
    }
 }

And a child class like below where getText() is returning a field that will never change.

public ChildClass extends BaseClass {
       private String text = "blah";

       @Override
       public String getText() {
           return text;
       }
   }

Is there any advantage/disadvantage to converting to the below instead?

public abstract class BaseClass {
   abstract String getText();

   private String text;

   public void printText() {
      System.out.println(text);
   }

   @PostConstruct
   public void postConstruct() {
      this.text = getText();
   }
}
Laurel
  • 5,965
  • 14
  • 31
  • 57
John Doe
  • 1
  • 2
  • It depends if you're expecting `getText()` to be an expensive call, and whether it can return different results on different calls. – shmosel Oct 05 '16 at 21:41

1 Answers1

0

Regarding the use of PostConstruct, and I will refer you to this question to elaborate on that part, but essentially in combination with dependency injection/polymorphic methods it can make sense to use it to make sure you have a fully initialized object.

In general I would say the two approaches you suggest are not equivalent, because the classes have different behavior. For your second class it is guaranteed that for every call to printText() the same text will be printed, whereas for your first version, the text may be different every time, since the implementation of getText() is delegated to the implementing child-class. Thus the second version has an invariant the first one does not. Whether or not this is desirable or not is another question you need to evaluate in your concrete context.

Community
  • 1
  • 1
midor
  • 5,487
  • 2
  • 23
  • 52