我已经创造了一些界面,使得界面:调用类的方法为
public interface A{
}
,我想打电话,我在B类接口已经实施的方法A使得:
public class B{
public boolean a(){
return true;
}
}
public interface A{
public void call {
a();
}
}
没有任何错误,请帮忙吗?
我已经创造了一些界面,使得界面:调用类的方法为
public interface A{
}
,我想打电话,我在B类接口已经实施的方法A使得:
public class B{
public boolean a(){
return true;
}
}
public interface A{
public void call {
a();
}
}
没有任何错误,请帮忙吗?
你想要做的事严格来说是不可能的,因为你不能在接口中定义方法实现。通过定义扩展B的接口的实现,你可以得到类似的东西。希望这足够接近。
public class AImplementation extends B implements A{
public void call(){
a();
}
}
我同意@Davis Broda的答案,在接口中没有办法定义方法。但我有另一种方法来解决这个问题。
您可以拥有该接口,然后让抽象类实现此接口,然后让所有其他类扩展抽象类。抽象类不必从要调用方法的类扩展类,也可以从该类的实例中调用它。
public interface A {
void caller();
}
public class B {
public void callMe() {
}
}
public class AbstractA implements A {
private B b;
public AbstractA(B b) {
this.b = b;
}
@Override
public void caller() {
b.callMe();
}
}
这样,AbstractA的所有实现都可以调用B的callMe方法。你可以使用此代码的接口直接访问此:
A anInstance = someInstance;
anInstance.caller();
如果您使用任何Java版本8之前,然后用@tinker和@Davis布罗达的答案棒。它们提供了更好的设计,因为它们不会将您的界面与B类耦合。但是,如果你坚持使用java 8,你可以在接口中使用默认的方法实现以及静态方法。
如果你的方法是继承,那么你必须使用默认方法。添加默认关键字:
default void call() {
...
}
现在的问题是,如何才能调用该方法,因为你不能在接口实例字段获取到类的引用。你有两个选择:
传递B的对象作为方法参数:
public interface A{
default void call(B b) {
b.a();
}
}
或使该方法B中静态
public interface A{
default void call() {
B.a();
}
}
如果你的方法是不是继承,但只是一个实用程序比你可以使它静态为:
public interface A{
public static void call() {
B.a();
}
}
你的问题不是很清楚,但如果我是g说得没错,你想要接口A
是一种普通的调用者。
如果您使用的是Java 8中,可以achive,使用方法参考:
public class B {
public boolean a() {
return true;
}
}
public interface A<T> {
default T call(Supplier<T> s) {
return s.get();
}
}
public class AImpl
implements A<Boolean> {
}
public class Sample {
public static void main(String[] args) {
AImpl a = new AImpl();
B b = new B();
boolean result = a.call(b::a);
System.out.println(result); // true
}
}
它使用Supplier<T>
因为你的方法a()
在B
类返回boolean
并且不接受任何参数。
请澄清你的问题。 – 2015-03-13 14:26:22
接口是占位符类。事情实现接口,但接口不或不应该(如果适用)有自己的任何逻辑。 – 2015-03-13 14:31:42