一个接口有多个实现类,并且不在一个包里
时间: 2023-12-10 07:38:09 浏览: 36
这种情况下可以使用Java接口和实现类的方式来实现。首先需要定义一个接口,接口里定义需要实现的方法。然后在不同的包中实现该接口的实现类。这样就可以在不同的包中使用相同的接口来调用不同的实现类了。
示例代码:
```java
// 定义接口
public interface MyInterface {
void doSomething();
}
// 实现类1
package com.example.impl1;
public class MyImpl1 implements MyInterface {
@Override
public void doSomething() {
// do something in implementation 1
}
}
// 实现类2
package com.example.impl2;
public class MyImpl2 implements MyInterface {
@Override
public void doSomething() {
// do something in implementation 2
}
}
// 使用
package com.example.app;
import com.example.impl1.MyImpl1;
import com.example.impl2.MyImpl2;
public class MyApp {
public static void main(String[] args) {
MyInterface impl1 = new MyImpl1();
MyInterface impl2 = new MyImpl2();
impl1.doSomething();
impl2.doSomething();
}
}
```
在上面的示例中,`MyImpl1`和`MyImpl2`实现了`MyInterface`接口,并且分别位于`com.example.impl1`和`com.example.impl2`两个包中。在`MyApp`类中,我们可以通过实例化`MyImpl1`和`MyImpl2`来调用不同的实现类。