簡體   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