Paul Vergeev Paul Vergeev - 1 year ago 57
Java Question

How to store subclass-specific information?

I have an

abstract class A
and I want it to enforce its subclasses to have
String Title
String Description
properties. So if
B extends A
, B is guaranteed to have property Title with a value that's the same across all the instances of B.

If Java permitted static abstract methods (that is, static methods that have to be in every subclass), I'd just write

public abstract class A {
public static abstract String getTitle();
public static abstract String getDescription();

The best idea I've come up with so far is to use separate enumeration which stores Title and Description for each subclass. That way I can look through all the
s with a single loop and instantiate a subclass with the title I need (this is the desired behavior). Unfortunately, that way I'll have to change the enum every time I add a subclass. Is there a better way?

Answer Source

Forget about mixing static stuff and inheritance. Just calls for trouble.

Instead, you turn to OCP

abstract class A { 
   public final String getTitle () { return getTitleInternal(); }
   abstract String getTitleInternal();

class B extends A {
   String getTitleInternal { maybe return some static value of B }

Please note that this is "better" than putting protected fields on class A. The essence of OO and inheritance is about behavior (so, you were correct in saying that you want certain methods on your subclass).

EDIT: after reading your comments again; I am tempted to remind you on

a) using interfaces

b) focusing on composition over inheritance