我有两个java类文件
Hi.java属于第二个包
package second;
public class Hi {
protected int v=20;
protected void m(){
System.out.println("i am protectTED");
}
}
属于第一个包的S.java
package first;
import second.Hi;
interface i1
{
void m();
int a=200;
}
interface i2{
void m1();
int b=100;
}
class S extends Hi implements i1,i2
{
int a=50;
public void m()
{
System.out.println("hi");
}
public void m1()
{
System.out.println("hello");
}
public static void main(String[] args) {
S s=new S();
/*need correction here (i don't know the exact syntax to mention to get
the desired output)
s.m(); //should invoke method m() from class Hi only.
s.m(); //Should invoke method m() from class S only.
*/
//the following statements prints the desired values
s.m1();
System.out.println(s.v);
System.out.println(i1.a);
System.out.println(s.a);
System.out.println(b);
}
}
当我运行 S.java 类文件中的方法 m() 时,类 Hi 应该被调用。(“我的意图”)而不是同一个类的方法 m(),即,类 S 被调用。
如何区分两种调用方式。这可能吗?
最佳答案
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
正确,因为您已使用 S
中的 m
覆盖了它。重写方法与重写字段有本质上的不同。 (一般来说,最好避免覆盖子类可见的任何字段,就像使用 a
一样。)
在S
中的实例代码中,可以通过super
运行继承的m
:super .m()
。但你不能从静态代码中做到这一点,甚至不能从 S
中的静态代码做到这一点。您可以在 S
中给自己一个私有(private)的 callSuperM
:
private void callSuperM() {
super.m();
}
...然后在 main
中使用它:
s.callSuperM(); // "i am protectTED"
s.m(); // "hi"
关于java - 调用从另一个类继承的方法时存在歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45545306/