[英]How a java class can extend another class and implement interface same time with same method name
I have an interface(A) the contain method myMethod() and a class(B) also contain the same method myMethod() and another class(c) extends and implement A and B.我有一个接口(A)包含方法 myMethod()和一个类(B)也包含相同的方法 myMethod()和另一个类(c)扩展并实现 A 和 B。
No i created the object of class A a = new C()
and call the a.myMethod();
不,我创建了类
A a = new C()
的对象A a = new C()
并调用了a.myMethod();
. .
How it is executing the myMethod of class B.它是如何执行 B 类的 myMethod 的。
interface A {
void myMethod();
}
class B {
public void myMethod() {
System.out.println("My Method");
}
}
class C extends B implements A {
}
class MainClass {
public static void main(String[] args) {
A a = new C();
a.myMethod();
}
}
Output of the program -程序的输出 -
My Method
The methods have the same signature.这些方法具有相同的签名。 This means, that the methods look the same, after all types have been reduced to their most compact form, and all (seemingly) redundant information has been removed during compilation.
这意味着,在所有类型都减少到它们最紧凑的形式之后,这些方法看起来是一样的,并且在编译过程中删除了所有(看似)冗余信息。 It is what is ultimately 'precompiled' to the
.class
files.它是最终“预编译”到
.class
文件的内容。
What the compiler remembers about the interface method: name: myMethod, returns: void, parameters: {}
编译器对接口方法的记忆:
name: myMethod, returns: void, parameters: {}
What the compiler remembers about the interface method: name: myMethod, returns: void, parameters: {}
编译器对接口方法的记忆:
name: myMethod, returns: void, parameters: {}
(For both methods, the compiler also remembers, that they are instance-methods, as opposed to static methods, and therefore there actually is a parameter [the 'this' object]. But this is only interesting much later in your developer life :)) (对于这两种方法,编译器还记得,它们是实例方法,而不是静态方法,因此实际上有一个参数 ['this' 对象]。但这只是在您的开发人员生活中很晚才有趣: ))
So in essence, they are the same method, to the compiler.所以本质上,它们对编译器来说是相同的方法。 In other words, the class you extend covers that method for you, and you do not have to implement it explicitly.
换句话说,您扩展的类为您覆盖了该方法,您不必显式实现它。 You can however (if you wish to) override the behavior of your extended class
B
and do something else, if required.但是,如果需要,您可以(如果您愿意)覆盖扩展类
B
的行为并执行其他操作。
First it will look for implementation of myMethod() in class C. since it is not there it will check in your extended class B. Then it will execute that class B myMethod().首先它会在类 C 中寻找 myMethod() 的实现。因为它不在那里它会检查你的扩展类 B。然后它会执行类 B myMethod()。 But if you have implemented myMethod() in class C your program will execute class C myMethod().
但是,如果您在 C 类中实现了 myMethod(),您的程序将执行 C 类 myMethod()。
The executed method depends on the type of the object and not the variable (polymorphism).执行的方法取决于对象的类型而不是变量(多态)。 In your case the object is of type
C
which inherits the implementation of myMethod
from type B
.在您的情况下,对象的类型为
C
,它从类型B
继承了myMethod
的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.