throwz
throwz

Reputation: 3

Limiting Subclass Field Type

Seems like a painfully simple problem I cannot find an answer to. Let's say there's a box:

public class Box {
    Object contents;
    ...
}

I want to make a subclass of Box that will only store a subtype of Object, like a String:

public class StringBox extends Box {
    String contents;
    //added fields/methods
    ... 
}

But that shadows the contents in StringBox's parent, which is not what I want to do. I could use an if statement or something, but that seems like a poor workaround. I also know that one could use generics and only have a Box< T> class, but I would like to have subclasses with extra functionality. And I do not know of abstract fields either, so I am at a bit of a loss.

If it's not clear, I'm looking for a good way to limit a field inherited by a super class to a particular subtype. If I am missing something obvious, or a better way to do things, I apologize.

Upvotes: 0

Views: 74

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

And I do not know of abstract fields either

There's no such thing as abstract field. Only methods (an classes, respectively) can be abstract.

I also know that one could use generics and only have a Box<T> class, but I would like to have subclasses with extra functionality.

A generic Box<T> could be actually your best friend in this case. Also, if your Box class just exposes some abstraction, you could just transform in to a generic interface:

public interface Box<T> {
    T getContent();
}

public class StringBox implements Box<String> {

    private String contents;

    String getContent();
}

Upvotes: 1

Related Questions