James Sumners
James Sumners

Reputation: 14785

Field of generic type with getter that returns the right type?

Given the following two classes Foo and FooBar:

public abstract class Foo {
  private String type;
  private int id;

  public String getType() {...}
  public int getId() {...}
}

public class FooBar extends Foo {
  private String extraField;

  public String getExtraField() {...}
}

How do I implement a class with a field that could be either Foo or FooBar? For example, in the class Example below, I want the getFoo() method to return either an instance of Foo or an instance of FooBar such that all accessors are available:

public class Example {
  private Foo fooField;

  // Not correct!
  public Foo getFooField() {...}
}

I am thinking that I need to implement a generic class as a wrapper, but I'm not sure how to tie it into the Example class.

public interface FooWrapper<T extends Foo> {
  // Would I define some getter here?
  // Is this the right track?
}

Update: For clarification, Example does not extend Foo. Example is a completely different type that contains a field of type Foo/FooBar.

Upvotes: 0

Views: 53

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213311

You can make your Example class generic like so:

class Example<T extends Foo> {
    private T fooField;
    public T getFooField() { return fooField;}
}

And then create parameterized instance, for Foo or FooBar:

Example<Foo> fooExample = new Example<Foo>();
Foo foo = fooExample.getFooField();
System.out.println(foo.getId());
System.out.println(foo.getType());

Example<FooBar> fooBarExample = new Example<FooBar>();
FooBar fooBar = fooBarExample.getFooField();
System.out.println(fooBar.getId());
System.out.println(fooBar.getType());
System.out.println(fooBar.getExtraField());

Upvotes: 2

Related Questions