gpt4 book ai didi

Java - 在 Eclipse 中合并两个类

转载 作者:行者123 更新时间:2023-12-01 10:18:53 25 4
gpt4 key购买 nike

我有两个类似的类(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com