【问题标题】:Inheritance and generics java android继承和泛型 java android
【发布时间】:2012-08-15 02:52:02
【问题描述】:

继承和泛型的新手,如果我的问题很愚蠢,请多多包涵:

我有以下几点:

public abstract class car {
    private long id;
    private String name;

    public car (long id, String name) {
        this.id = id;
        this.name = name;
    }

    public final long getID(){
        return id;
    }

    public final String getName(){
        return name;
    }
}

public class sedan extends car {
    public sedan(long id, String name) {
        super (id, name);
    }
    ...
}

public class jeep extends car {
    public jeep(long id, String name) {
        super (id, name);
    }
    ...
}

我正在尝试为微调器扩展 ArrayAdapter,如下所示:

public class DropdownAdapter extends ArrayAdapter<car> {
    private Context context;
    private List<car> values;

    public DropdownAdapter(Context context, int textViewResourceId, List<car> values) {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }
    ...
}

当我尝试使用它时,问题就来了:

adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstSedan);

会给我错误:构造函数 DropdownAdapter (ScreenItemList, int, List) is undefined

adapter = new DropdownAdapter (this, android.R.layout.simple_spinner_item, lstJeep);

会给我错误:构造函数 DropdownAdapter (ScreenItemList, int, List) 是未定义的

这里有什么问题?当 lstSedan 或 lstJeep 从汽车派生时,为什么我不能使用它们作为参数?我该如何解决这个问题?谢谢!

【问题讨论】:

    标签: android generics inheritance abstract-class extend


    【解决方案1】:

    您定义了一个需要List&lt;a&gt; 类型参数的方法

      public SpinnerAdapter(Context context, int textViewResourceId, List<a> values)
    

    也就是说,它需要a 类型的项目列表。 但是随后您传递了一个继承 ab 类型的参数,而不是 List&lt;b&gt; 类型的参数 尝试使用这种方式:

      List<b> lstB= new ArrayList<b>();
      adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);
    

    正如 JoxTraex 所说,您应该阅读java name convention

    更新
    对不起,我弄错了。因为java不允许将List&lt;ChildClass&gt;参数传递给List&lt;ParentClass&gt;,所以在这种情况下你不应该使用继承。尝试使用泛型

    public class DropdownAdapter extends ArrayAdapter<T> {
    private Context context;
    private List<T> values;
    
    public DropdownAdapter(Context context, int textViewResourceId, List<T> values) {
        super(context, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }
    ...
    }
    

    这个函数调用应该可以工作:

     adapter = new SpinnerAdapter (this, android.R.layout.simple_spinner_item, lstB);
    

    【讨论】:

    • 嗨 R4j。还是不行,不知道是什么问题。我得到了同样的错误,我实际上有一个错字并且已经使用了一个列表
    【解决方案2】:

    这是因为您拥有它的名称,特别是 SDK 中存在 SpinnerAdapter ALREADY。您需要明确说明您使用的是哪一个或更改类名。

    建议

    另外,仅供参考,您不应该将类称为 A 之类的无用名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 1970-01-01
      相关资源
      最近更新 更多