I have a class that is abstract with a couple of abstract methods and I need all the classes that inherit from it to have a final static String field which contains the 'simple' name of the child class, called TAG. I have been trying several ways, but they all prevent me from compiling.
Is this possible to do? And if so, how is it done?
So it works for me, but I don't want it done as a field of the instance.
abstract class A{
protected final String TAG;
public A() {
TAG = getClass().getSimpleName();
}
}
I want to get the TAG from the child class as if it were from the class, not from the instance, like this:
class B extends A {
public void mostrar() {
System.out.println(B.TAG);
}
}
To your question, YES , it is possible to have a dynamic constant as you need, here you can see a discussion (in English)
Answered this, in my opinion, I think you don't need a constant for your purpose, basically because you will complicate your life since you have an abstract class, a final constant and inherited classes...
I propose 2 alternatives (see how I get it
getSimpleName()
in both cases if you want to make variations)Method 1 (inheriting, with method, not statically)
Let's take 2 example classes:
And a main:
EXIT:
Method 2 (inheriting, without method, statically)
Having a class structure like yours, without method or constant you can directly have the data you want like this:
EXIT:
The way to do what you want can be through inheritance, creating a method which gets the name of the class:
Having as output: