繁体   English   中英

用Java中的超级构造函数调用方法,对吗?

[英]Calling method off of super constructor in Java, is it right?

如果我有一个带有两个参数的构造函数,可以这样调用super吗?

super(a,b).method

例如:

public class Money (){
     int euro=0;
     int count=0;  

     public Money(int a,int b) {
        a=euro;   
        b=count;
     }

     public int getPay(){
       return 100;
     }
}

public class  Pay extends Money{
   super(a,b).getPay();

}

这可能吗?

这是不可能的,没有任何意义。 如果getPay()是父类的方法,则子级可以使用该方法,并且在子级重写该方法的情况下,可以将其称为getPay()或类似super.getPay()的方法。

不,但是你可以打电话

public class  Pay extends Money{

   public Pay(int a,int b){
     super(a,b);
    }

}

然后做

new Pay(1,4).getPay();

不完全是。 但是,您似乎正在尝试做两件事:

  • 使用超级构造函数(Money)定义Pay构造函数
  • 调用getPay()的超级版本(钱)时,请调用该版本。

如果是这样,那么您要做的是:

public class Money (){
     int euro=0;
     int count=0;  

     public Money(int a,int b) {
        a=euro;   
        b=count;
     }

     public int getPay(){
       return 100;
     }
}

public class  Pay extends Money{
   public Pay(int a, int b) {
       super(a, b);
   }

   public int getPay() {
       //This is redundant, see note below
       return super.getPay();
   }

}

注意:此时,调用super.getPay() getPay()完全是多余的(因为您要覆盖super.getPay(),否则,无论如何您都可以访问它)。 但是您现在可以做的是修改方法(例如, return super.getPay() + someVariable; )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM