[英]Calling method off of super constructor in Java, is it right?
If I have a constructor with two arguments, can I call super like this? 如果我有一个带有两个参数的构造函数,可以这样调用super吗?
super(a,b).method
For example: 例如:
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();
}
Is this possible? 这可能吗?
It is not possible and does not make any sense. 这是不可能的,没有任何意义。 If
getPay()
is the parent class' method, it will be available to the child and can be called as such getPay()
or like super.getPay()
in case the child overridden the method. 如果
getPay()
是父类的方法,则子级可以使用该方法,并且在子级重写该方法的情况下,可以将其称为getPay()
或类似super.getPay()
的方法。
No, but you can call 不,但是你可以打电话
public class Pay extends Money{
public Pay(int a,int b){
super(a,b);
}
}
and later on do 然后做
new Pay(1,4).getPay();
Not exactly.
不完全是。 However, it seems that you are trying to do two things:
但是,您似乎正在尝试做两件事:
If so, then what you want to do is this: 如果是这样,那么您要做的是:
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();
}
}
Note: getPay()
calling super.getPay()
is totally redundant at this point (because you're overriding super.getPay(), and if you didn't you'd have access to it anyway). 注意:此时,调用
super.getPay()
getPay()
完全是多余的(因为您要覆盖super.getPay(),否则,无论如何您都可以访问它)。 But what you can do now is modify the method (for example, return super.getPay() + someVariable;
). 但是您现在可以做的是修改方法(例如,
return super.getPay() + someVariable;
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.