【问题标题】:Array of classes implementing an interface to call same method实现接口以调用相同方法的类数组
【发布时间】:2019-03-12 20:16:13
【问题描述】:

我有 4 个类,都实现了一个接口 IntSorter。所有类都有一个sort 方法,所以对于每个类我想在一个数组上调用sort

我认为这样的事情会起作用:

IntSorter[] classes = new IntSorter[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

但是classes 不能保存.class 名称,我收到错误Type mismatch: cannot convert from Class<Class1> to IntSorter

所以我尝试了

Class[] classes = new Class[] {
Class1.class, Class2.class, Class3.class, Class4.class
};
for (Class c : classes)
    c.sort(array.clone());

但是现在 c.sort() 不能被调用。我首先尝试使用(IntSorter) c 将类解析为 IntSorter,但随后出现错误Cannot cast from Class to IntSorter

我该如何解决这个问题?

【问题讨论】:

  • 如果 IntSorter 是一个接口,则数组 IntSorter[] 必须使用实现 IntSorter 的对象进行初始化。第一个例子更接近你想要的。但是,不是将几个类对象放入 IntSorter[],而是放入这些类的实例。
  • 类似这样的东西:IntSorter[] sorters = new IntSorter[] { new Sorter1(), new Sorter2(), new Sorter3() new Sorter4() };.

标签: java class interface


【解决方案1】:

您正在尝试创建类数组,而不是实现 IntSorter 的类实例数组。

检查此问题以了解类、对象和实例之间的区别:The difference between Classes, Objects, and Instances

据我所知,可用信息有限,您的代码应如下所示:

IntSorter[] classes = new IntSorter[] {
new Class1(), new Class2(), new Class3(), new Class4()
};
for (IntSorter c : classes)
    c.sort(array.clone());

【讨论】:

    【解决方案2】:

    使用第一种方法,但您想要for (IntSorter c : classes) - 您需要将实例放入数组(而不是类)中。类似的,

    IntSorter[] classes = new IntSorter[] {
        new Class1(), new Class2(), new Class3(), new Class4()
    };
    for (IntSorter c : classes) {
        c.sort(array.clone());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2019-04-08
      相关资源
      最近更新 更多