4

I was wondering: what would be the best way to fit an attribute to a class which is part of a large inheritance structure. I wanted to make an abstract static method which each class would override but after a quick google that doesn't seem to work. Any suggestions?

I could make it an instance method but it really is a class level specification.

Thanks in advance.

Michiel Ariens
  • 288
  • 4
  • 12

1 Answers1

3

I would suggest you create an abstract method, just as you have thought of, and let this method be implemented in terms of static variables in each class.

abstract class Base {
    abstract String getValue();
}

class A extends Base {

    static String aValue = "From A";

    String getValue() {
        return aValue;
    }
}

class B extends A {

    static String bValue = "From B";

    String getValue() {
        return bValue;
    }
}

It requires a little bit more boiler plate in each class, than just a field declaration, but I believe it is hard to do anything about that.

aioobe
  • 413,195
  • 112
  • 811
  • 826