【发布时间】:2012-01-14 08:28:54
【问题描述】:
我在 Google 上搜索时发现了这段代码:
public interface Combine {
// Combines 2 objects
public Object combine(Object o1, Object o2);
}
我想使用上面的代码在主类中组合两个对象。我将如何声明一个 Combine 对象来达到我的目的?
【问题讨论】:
我在 Google 上搜索时发现了这段代码:
public interface Combine {
// Combines 2 objects
public Object combine(Object o1, Object o2);
}
我想使用上面的代码在主类中组合两个对象。我将如何声明一个 Combine 对象来达到我的目的?
【问题讨论】:
您将创建一个实现Combine 接口的类,并覆盖public Object combine(Object o1, Object o2) 以在您的情况下执行合并这两个参数的任何操作。
class Droplet implements Combine {
@Override
public Object combine(Object dropOne, Object dropTwo) {
//write combine code for droplets and return a newly combined droplet
}
}
查看Marcelos 答案以获得使用泛型的更出色的解决方案 - 这允许您传递您感兴趣的特定类型,而不仅仅是Object。
【讨论】:
根据类别,“组合”的逻辑会发生变化。首先,类需要实现Combine接口,然后还要为combine()方法编写逻辑,例如:
public interface Combine<T> {
// Combines 2 objects
public T combine(T o1, T o2);
}
public class BagOfOranges implements Combine<BagOfOranges> {
private int quantity;
public BagOfOranges(int quantity) {
this.quantity = quantity;
}
public BagOfOranges combine(BagOfOranges b1, BagOfOranges b2) {
return new BagOfOranges(b1.quantity + b2.quantity);
}
}
【讨论】:
这只是一个界面。它没有描述实现。你需要创建一个implements Combine的类。
public Foo implements Combine {
// snip...
public Object combine(Object o1, Object o2) {
// You need to implement this method.
}
}
【讨论】:
试试这个:
public class Combineinator implements Combine
{
public Object combine(
final Object object1,
final Object object2)
{
// implementation details left to the student.
}
}
【讨论】:
public class MyCombiner implements Combine {
public Object combine (Object o1, Object o2) {
//logic to combine the objects goes here (i.e. the hard part)
}
}
换句话说,您需要实际编写代码来组合对象,然后将其置于上述形式。如果您需要有关组合两个特定对象的建议,您应该在单独的问题中提出。
【讨论】:
您给定的代码只是一个接口。您需要实现它来定义您的“组合对象”
一个简单的实现可能是这样的。
这里的 CombinedObjs 只是保留了需要组合的对象的引用。
public class CombinedObjs implements Combine {
private Object Object1 = null;
private Object Object2 = null;
public Object combine(Object o1, Object o2){
this.Object1 = o1;
this.Object2 = o2;
return this;
}
// You can provide setters to get the individual objects
public Object getObject1(){
return this.Object1;
}
public Object getObject2(){
return this.Object2;
}
}
【讨论】:
您不能创建 Combine 对象的实例,因为它是一个接口。您应该创建一个自己的类来扩展 Combine 接口。
【讨论】:
new ActionListener() { public void actionPerformed(ActionEvent e){...}}怎么样?