Java - 在 Eclipse 中合并两个类

标签 java eclipse merge

我有两个类似的类(class)。我想将它合并为一个。这些类的对象被用在许多不同的地方。是否可以在 Eclipse 中安全地完成此操作?

最佳答案

如果您有两个在某些方面相似(但在其他方面可能不相似)的类,则可以创建一个接口(interface)来描述它们共同的方法。然后,您将让两个类实现该接口(interface)。在应用程序的其他地方,您可以引用接口(interface)作为方法的形式参数。这是一个示例(请参阅下面的代码)。

在 IDE 中没有自动方法来执行此操作 - 您必须花时间手动设计对象层次结构(类之间的关系以及应用程序将用于与它们交互的 API) .

public Interface Automobile{
    //define an interface that describes the methods common to your two classes

    public void drive();
}

//this is one of your two classes 
public class Sedan implements Automobile{
    public void drive(){
        //Sedan-specific implementation here
    }
}

//here's the other one. It's similar in that it has a drive method, but different
//in that it's implementation for drive() is different, and there might be 
//other stuff in this class that is different from Sedan. However, it still is-an
//Automoblie
public class RaceCar implements Automobile{
    public void drive(){
        //RaceCar-specific implementation here
    }
}

public class YourApplication{

    //some method that accepts either one of the two classes you 
    //described as being "similar"
    public void someMethod(Automobile automobile){
        //you could pass in either a Sedan or a RaceCar, and
        //the corresponding drive() method would get called
        automobile.drive(); 
    }

    public static void main(String args[]){
        Automobile car1 = new Sedan();
        Automobile car2 = new RaceCar();

        someMethod(car1);
        //call the same method, but with car2!
        someMethod(car2);
    }
}

关于Java - 在 Eclipse 中合并两个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746262/

相关文章:

java通用模板错误

java - SWT下的Swing组件可以加速吗?

java - 如何在 Java 中播放波形 (wav) 文件

java - 如何使用合并函数将元素添加到 HashMap<K, List<V>>

Java 7 监视服务 : avoiding an infinite loop of events when changing the event source in handler

java - @jsonRootName 不适用于 Spring Boot 启动器 hatoas

python - 与 Pandas 合并的重复列?

GIT 将文件从 dev 重新 merge 到 master

javax.naming.NamingException : JBAS011843: Failed instantiate InitialContextFactory org. jnp.interfaces.NamingContextFactory 来自类加载器

c++ - Eclipse C++ 控制台 IO 运行/调试问题