Pavel Vergeev
Pavel Vergeev

Reputation: 3370

How to store subclass-specific information?

I have an abstract class A and I want it to enforce its subclasses to have String Title and 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 Titles 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?

Upvotes: 0

Views: 52

Answers (2)

GhostCat
GhostCat

Reputation: 140427

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 {
   @Override
   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

Upvotes: 2

Vlad Călin Buzea
Vlad Călin Buzea

Reputation: 559

Did you think of using protected fields?

public abstract class A {
    protected String title;
    protected String description;
}

This way the two fields are visible in any class that extends A.

public abstract class B extends A {
        public B(){
            title = ...
            description = ....
        }

    }

Upvotes: 1

Related Questions