Sergi Juanola
Sergi Juanola

Reputation: 6647

Override class variable/method on inherited classes

I've defined a class, and I'd like to have a class method (or variable, I don't really care) which needs to be overriden by each inherited class. My best approaches have been unsuccessful:

public abstract String getHumanString();, as abstract methods can't be static

public static String getHumanString();, as static methods can only be hidden, not overriden.

I don't know if there is another trick I could use. I could also be happy to automatically define getHumanString() by myself on the parent class with something like humanize(class.getClass().getName()) (I'd just make getName() look more beautiful, according to my needs), getName() is not accessible on static methods. So, to sum up, my question is:

1. Can I have a static method/variable which could be edited on subclasses?

OR, as another valid solution:

2. Can I create a static method that plays with its own class name?

Thanks in advance.

EDIT:

Imagine this situation (I'll skip useless lines, as I'm directly writing code here):

class ParentClass {
    public static (or whatever) String getHumanString() {
        return "My Parent Class";
    }

    public static showMyInfo() {
        System.out.println(getHumanString());
    }
}

class ChildClass {
    @Override
    public static (or whatever) String getHumanString() {
        return "My Child Class";
    }
}

...

public static void main()
{
   ChildClass.showMyInfo();
}

It should output (as I'd want) "My Child Class", but it actually outputs (as you all know) "My Parent Class".

Upvotes: 1

Views: 715

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533492

If this is a requirement I would suggest splitting the static members and fields into a class(es) of their own. This way your existing class can refer to a single static instance of a class which is polymorphic.

Upvotes: 0

Thilo
Thilo

Reputation: 262484

I'd like to have a readable name for each class (not just getClass().getName()), which does not depend on the object instance. In fact, I'd like to avoid instancing that class when I need getHumanString().

Have a properties file, with class name as key and human string as value. And a single static method somewhere to read it.

 static String getHumanString(Class<?> clazz){
     return humanStrings.getProperty(clazz.getName(), clazz.getSimpleName());
 }

Also lends itself to localization if necessary. Plus you can "enhance" existing classes whose definition you cannot change.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500155

Static methods aren't polymorphic, no. Nor are variables, by the way - you can't override variables, even instance ones. You can hide them, but not override them.

It's not really clear what you're trying to do, to be honest - but you may want to consider a corresponding type hierarchy so that the static methods become instance methods in the new types.

Upvotes: 4

Related Questions