I want to create a method printKlass()
in my top-level class which is inherited and prints a top-level variable KLASS
containing the value of getClass().getSimpleName()
.
So, in the case of class A, the printKlass
method should write A
.
And class B should print B
.
But the compiler won't let me access the getClass
method in the part class - it says this
is not available in a static
context.
How do I get around this?
public class A
{
protected static final String KLASS = this.getClass().getSimpleName(); // "Cannot use 'this' in a static context
protected
public void printKlass()
{
System.out.println(KLASS);
}
}
publ开发者_开发知识库ic class B extends A
{
//...
printKlass(); // Should say "B", not "A"
//...
}
As a static field, it cannot have different values for different classes.
What's wrong with ?
public void printKlass()
{
return System.out.println(getClass().getSimpleName());
}
精彩评论