Search code examples
androidabstract-classfinal

How to force a class to declare a final variable?


For the moment, I created an abstract class like this:

public abstract class MyClass {
    public final static String TAG;
    ...
}

But it gives me an error of not initializing a final variable. Then I tried to initialize it from a constructor, but it didn't work either (gives the same error plus another one of trying to set a value to a final variable), although many stackoverflow posts says that really works...

public abstract class MyClass {
    public final static String TAG;

    public MyClass(String u){
        this.TAG = u;
    }
}

It seems like final variables have to be assigned only when declaring the variable. Is this correct? How can I achieve this?


Solution

  • you can't because of the static keyword. static final gives you the assurance that the value of the variable will not change for the whole life cycle of the application. When you try to initialize it in the constructor you are bounding its value to the particular instance, defeating the concept of constant. Since you want to have a different value for every subclass you could change your code like:

    public abstract class MyClass {
        protected final String mTag;
    
        public MyClass(String u){
            mTag = u;
        }
    }
    

    this way mTag only accessible only from MyClass's subclasses. Or you could also declare it a constant in every subclass, omitting the constructor's intialization. E.g

    public final static String TAG = YourClassName.class.getSimpleName();