Muco
Muco

Reputation: 27

Generics and inheritance in java

I have a tiny problem using (what I assume are) generics. I have this code:

public class A{
  private String name;

  public String getName(){
    return this.name;
 }
}


public class B extends A{
  private String street;

  public String getStreet(){
    return this.street;
 }
}

public class C extends A{
  private int number;

  public int getNumber(){
    return this.number;
 }
}

And I'd like to create new classes that will look like this :

public class AChange{
  private A instance;

  public String doSomething(){
    return A.getName();
 }
}

public class BChange extends AChange{

  public String street(){
    return A.getStreet();
 }
}

public class CChange extends AChange{

  public int number(){
    return A.getNumber();
 }
}

And of course, A class doesn't have those methods, but the subclasses do. How can I write this code, so it will work the way I want it to?

Upvotes: 0

Views: 81

Answers (2)

zapl
zapl

Reputation: 63955

You can do the same without generics like so

static class AChange {
    private A instance;
    public AChange(A instance) {
        this.instance = instance;
    }
    public String doSomething() {
        return instance.getName();
    }
}

static class BChange extends AChange {
    private B instance;
    public BChange(B instance) {
        super(instance);
        this.instance = instance;
    }
    public String street() {
        return instance.getStreet();
    }
}

static class CChange extends AChange {
    private C instance;
    public CChange(C instance) {
        super(instance);
        this.instance = instance;
    }
    public int number() {
        return instance.getNumber();
    }
}

Instead of using a generic instance T, store a reference of the right type

Upvotes: 1

wero
wero

Reputation: 33010

Add a generic type parameter to AChange to be used as type of field instance:

class AChange<T extends A> {
    protected T instance;

    public String doSomething() {
        return instance.getName();
    }
}

and define it in BChange and CChange accordingly

class BChange extends AChange<B> {
    public String street() {
        return instance.getStreet();
    }
}

class CChange extends AChange<C> {
    public int number() {
        return instance.getNumber();
    }
}

Upvotes: 2

Related Questions