2014-03-26 30 views
0

我想打电话从儿子一个父类的方法调用父类的方法,我不知道父类的方法是如何工作的:由儿子覆盖,与儿子的另一种方法

A有方法:myMethod(double d)

public class B extends A{ 

    //overrides 
    public void myMethod(double d){ 
     doSomthing(); 
     super.myMethod(d); 
    } 

    public void anotherMethod(...){ 
     super.myMethod(d); 
    } 

} 

instanceOfB.myMethod(d)工作正常。问题是instanceOfB.anotherMethod(...)它只是做instanceOfB.myMethod(d)

我想要B的实例运行myMethod的父。
有什么建议吗?

+0

向我们提供的A级 – darijan

+0

你的意思的实现,'b.anotherMethod(...)'运行''A'的myMethod'? – Maroun

回答

0

你在做错事。它调用super.myMethod()。我组装这些代码很快测试

public class Test { 

    public static void main(String ... args) { 
     B b= new B(); 
     b.anotherMethod(); //the output is 1 which is correct 
     b.myMethod(2); //the output is somth and then 2 which is correct 
    } 

    public static class A { 
     public void myMethod(double d) { 
      System.out.println(d); 
     } 
    } 

    public static class B extends A{ 

     //overrides 
     public void myMethod(double d){ 
      doSomthing(); 
      super.myMethod(d); 
     } 

     private void doSomthing() { 
      System.out.println("somth"); 
     } 

     public void anotherMethod(){ 
      super.myMethod(1); 
     } 

    } 

} 
+0

我也这么认为。但是你的陈述与我的例子有什么关系?你向我们展示你认为好?这些是内部类 – darijan

+0

对不起,错误的评论 – Keerthivasan

+0

事情是我不知道如何写父方法.. –