我有一个简单的 Java 问题。考虑以下接口(interface):
interface A {
void work();
void a();
}
interface B {
void work();
void b();
}
所以当一个类要实现它们时,应该是这样的:
class Impl implements A, B {
void work() {
/*some business*/
}
void a() {}
void b() {}
}
我的问题是,在 work
方法中,我如何发现它是由 A
或 B
类型调用的?
C# 中的上述类将是这样的,这很好地将两个实现分开:
class Impl : A, B
{
void B::work() {}
void A::work() {}
void a() {}
void b() {}
}
但是我如何在 Java 中实现类似 C# 模型的东西呢?!
提前致谢。
最佳答案
都没有。 interface
的想法是实现它的类与接口(interface)暗示的“契约”一致。如果你有两个接口(interface),要求两者都实现一个方法 work()
,并且一个类实现这两个接口(interface),那么它必须实现 work()
以符合双方的契约(Contract)。
JavaDoc说:
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
这正是您通过实现 work()
方法所做的:您同时满足接口(interface) A
和 B
。
关于java - 如何找出在哪个接口(interface)上调用了方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20317448/