Search code examples
javaoopattributesabstract-classfinal

Initializing "Default" final attributes in Java abstract class


I have an abstract class which is supposed to have an (int) attribute that can't be modified after initialization and is pre-set to 1; what is the best way to do it? Should I make it final? The requirement is that inside the class I will have one and only one constructor(with parameters), and no setters. If so, how do I make it 1 by default if it's final and (I suppose) I'm going to initialize it in the constructor? Thanks!


Solution

  • As a matter of fact your can even hard code it, if it will always be a constant value.

    For example if your variable should always be 25 you can do something like this:

    public abstract class Test
    {
      protected final int pressure = 25;
    
      //Constructor
      public Test()
      {
        // TODO Auto-generated constructor stub
      }
    }
    

    But if you evaluate the value on runtime you need to set it with in the constructor of the Object:

    public abstract class Test
    {
      protected final int pressure;
    
      //Constructor
      public Test(int pressure)
      {
        this.pressure = pressure;
      }
    }
    

    Note that in this case the variable must not be assigned earlier!

    The question, if a final variable should be used depends on it's purpose. A final variable can only be assigned once over it's entire lifetime. If you have to modify it in any kind you should not use it.