解决这个问题的方法之一是使用抽象类(abstract class)或接口(interface)来定义通用接口,然后让不同类实现这个接口或继承这个抽象类。
以下是一个使用Java语言的示例:
首先,定义一个通用接口:
public interface CommonInterface {
void performAction();
}
然后,创建两个不同类分别实现这个接口:
public class ClassA implements CommonInterface {
@Override
public void performAction() {
System.out.println("ClassA performs action");
// ClassA的具体实现
}
}
public class ClassB implements CommonInterface {
@Override
public void performAction() {
System.out.println("ClassB performs action");
// ClassB的具体实现
}
}
最后,通过实例化不同的类对象,调用通用接口中的方法:
public class Main {
public static void main(String[] args) {
CommonInterface objA = new ClassA();
CommonInterface objB = new ClassB();
objA.performAction(); // 输出:ClassA performs action
objB.performAction(); // 输出:ClassB performs action
}
}
这样,不同类中的通用接口就能够被调用,并且每个类可以根据自身需求实现具体的行为。