Tuesday, July 14, 2015

Java: Overridable method call in constructor

In NetBeans, the following code will give a warning: Overridable method call in constructor.

public class Reward {
      protected int baseReward = 1000;

      public Reward() {
            int reward = calculateReward(); //this line generates the warning
            System.out.println("The reward is " + reward);
      }

      protected int calculateReward() {return baseReward;}
}

This is because the calculateReward method can be override in subclasses and calling such a method in superclass constructor before the proper initiation of properties in subclasses may result in errors. Here is an example.

public class CreativeReward extends Reward {
      private int rewardAdjust = 100;

     public CreativeReward() {
           super();
     }

      public CreativeReward(int rewardAdjust) {
            this.rewardAdjust = rewardAdjust;
      }

      protected int calculateReward() {
          return baseReward + rewardAdjust;
      }

      public static void main(String[] args) {
            new CreativeReward(); //Prints 1000 instead of 1100
            new CreativeReward(50); //Prints 1000 instead of 1050
      }
}

This is because the constructor in superclass is called first, after which the constructor in subclass is called and the instance variables are initiated. Therefore, an overriden method called in superclass constructor will ignore the values assigned to the used instance variables in subclasses. Thus, in the above example the rewardAdjust used in the superclass constructor is 0 instead of 100 or 50.

-----------------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.


No comments:

Post a Comment