简体   繁体   中英

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(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.

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();

However, it seems that you are trying to do two things:

  • Use the super constructor (Money) to define the Pay constructor
  • Call the super (Money) version of `getPay()` when you call this version of `getPay()`.

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). But what you can do now is modify the method (for example, return super.getPay() + someVariable; ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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