开发者

How to display the SimpleClassName at each level of the inheritance hierarchy using a method that is inherited?

开发者 https://www.devze.com 2023-03-18 13:19 出处:网络
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().

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());
}
0

精彩评论

暂无评论...
验证码 换一张
取 消