Search code examples
javaclassvariablesabstractfinal

Initializing a final variable in an abstract class (Java)


So I have this abstract class

 public abstract class A {

   protected final boolean b;

   protected A (boolean b){
    this.b = b;
   }

}

And this class that extends A

 public class C extends A{

   protected C() {
    super(false);
   }

}

I dont want "b" to be able to change its' value once it's initialized But I dont know how to do it without the compiler going haywire.

Any suggestions are welcome. Thanks in advance.

EDIT1: static removed from b.

EDIT 2: Ok realised the problem and fixed see above. Special thanks to J.Lucky :)


Solution

  • I'd suggest you make use of the final keyword.

    Try the following codes:

    abstract class A {
    
        final protected boolean b;
    
        A(boolean b) {
            this.b = b;
        }
    
        //No setter method
        //public abstract void setB(boolean b);
        public abstract boolean getB();
    }
    
    class C extends A {
    
        C(boolean b) {
            super(b);
        }
    
        @Override
        public boolean getB() {
            return b;
        }
    }
    

    Sample implementation would be:

    public static void main(String args[]) {
        C c = new C(true);
        System.out.println(c.getB());
    }
    

    Since b now is a final variable, you will be forced to initialize it on your constructor and you will not have any way of changing b anymore. Even if you provide a setter method for b, the compiler will stop you.

    EDIT 2:

    Say you created another class called 'D' and this time you know you want to set it to false by default. You can have something like:

    class D extends A {
        D() {
            super(false);
        }
    
        //You can also overload it so that you will have a choice
        D(boolean b) {
            super(b);
        }
    
    
        @Override
        public boolean getB() {
            return b;
        }
    
        public static void main(String[] args) {
            D defaultBVal = D();
            D customBVal = D(true);
    
            System.out.println(defaultBVal.getB()); //false
            System.out.println(customBVal.getB()); //true
        }
    }