调用从另一个类继承的方法时的歧义

时间:2017-08-07 11:00:12

标签: 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()时,应该调用。(“我的意图”)而不是相同类的方法m(),即调用类S.

如何区分2种调用方法。它甚至可能吗?

1 个答案:

答案 0 :(得分:1)

  

当我在类中运行S.java类文件方法m()时,应该调用。("我的意图")而不是相同类的方法m(),即调用类S

正确,因为您已在m中使用S覆盖了它。覆盖方法与覆盖字段根本不同。 (一般情况下,最好避免覆盖子类可见的任何字段,就像您使用a一样。)

S中的实例代码中,您可以通过msuper运行继承的super.m()。但是你不能用静态代码做到这一点,甚至不能用S中的静态代码。您可以在callSuperM中为自己设置私人S

private void callSuperM() {
    super.m();
}

...然后在main中使用它:

s.callSuperM(); // "i am protectTED"
s.m();          // "hi"
相关问题