简体   繁体   中英

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?

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();
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM