Is it possible to create a class constant when inheriting in Java?

3

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 field static String em> which contains the 'simple' name of the daughter class, called TAG. I've been trying it in various ways, but they all prevent me from compiling.

Is it possible to do it? And if so, how is it done?

So that it works for me, but I do not 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 daughter 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);
    }
}
    
asked by dddenis 17.08.2016 в 10:44
source

2 answers

3

To your question, YES , it is possible to have a dynamic constant as you need, here you can see a discussion (in English)

Answer this, in my opinion, I think you do not 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 the getSimpleName() in both cases if you want to make variations)

Method 1 (inheriting, with method, not statically)

public abstract class Q {
    public void mostrar() {
        System.out.println(this.getClass().getSimpleName());
    }
}

Let's take 2 example classes:

public class SubQ extends Q {
}

public class OtraQ extends Q {
}

And a main:

public static void main(String[] args) {
    SubQ sq = new SubQ();
    sq.mostrar();

    OtraQ oq = new OtraQ();
    oq.mostrar();
}

DEPARTURE:

SubQ
OtraQ

Method 2 (inheriting, without method, statically)

Having a class structure like yours, without a method or constant, you can directly have the data you want like this:

System.out.println(Q.class.getSimpleName());
System.out.println(SubQ.class.getSimpleName());
System.out.println(OtraQ.class.getSimpleName());

DEPARTURE:

Q
SubQ
OtraQ
    
answered by 17.08.2016 / 11:12
source
-1

The way to do what you want can be by inheritance, creating a method which gets the name of the class:

abstract class ClassA{


    public void mostrar() {
        System.out.println("Simple name: " + getClass().getSimpleName());
    }
}

class ClassB extends ClassA {

}

class ClassX extends ClassA {

}


public class myApplication {

    public static void main(String[] args) {
        ClassB b = new ClassB();
        b.mostrar();     
        ClassX x = new ClassX();
        x.mostrar();   
    }

}

Having as output:

Simple name: ClassB
Simple name: ClassX
    
answered by 17.08.2016 в 11:29