在java中组合2个对象 [英] combine 2 objects in java

查看:115
本文介绍了在java中组合2个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索此代码:

I found this code at a search on Google:

public interface Combine {
    // Combines 2 objects
    public Object combine(Object o1, Object o2);
}

并且我想使用上面的代码在主类中组合两个对象。如何声明一个Combine对象来满足我的目的?

and I would like to combine two objects in the main class using the above code. How would I declare a Combine object to serve my purpose?

推荐答案

您将创建一个实现 Combine 接口,并覆盖 public Object combine(Object o1,Object o2),以便在您的情况下执行任何操作来组合这两个参数。

You would create a class that implements the Combine interface, and override public Object combine(Object o1, Object o2) to do whatever it means in your case to combine those two parameters.

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

Look at Marcelos answer for a fancier solution using generics - this allows you to pass in the specific types you're interested in, and not just Object.

这篇关于在java中组合2个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆