java - 调用从另一个类继承的方法时存在歧义

标签 java

我有两个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/

相关文章:

java - 为什么java applet没有得到广泛应用

java - 从数组列表中安全地删除数据

java - 如何改进hibernate查询?

java - 使用 JOptionPane API 的自定义对话框不会被释放

java - Ant Tomcat 7 重新加载 FileNotFoundException

java - 带有 Java NoSuchElementException 超时的 Selenium WebDriver

java - Spring Security - 在重定向到登录时保留 URL 参数

Java - 使用 Hibernate (HBM) 在数据库中引用 Enum(数字值)

java - 从 Mongo DB Cursor 获取信息

java - C3P0:池已满