簡體   English   中英

在 Java 中,有沒有辦法在同一個構造函數中調用 this() 和 super()?

[英]In Java, is there any way to call this() and super() in same constructor?

我有兩個類,如下所示。 我想在單個構造函數 TestEmployee() 中訪問 this() 和 super() 構造函數。 當前方法無法編譯。 Java 中有沒有其他方法可以在同一個構造函數的主體中同時調用 this() 和 super()。

class Employee{
   double salary;
   Employee(double salary){
      this.salary = salary;
   }
}
class TestEmployee extends Employee{
   TestEmployee(){
        super(1000000);
        this(10000);
   }
   double bonus;
   TestEmployee(double bonus){
       this.bonus = bonus;
   }
}

顯然不行,super和this都必須是構造函數體的第一條語句。而且只能有一個第一條語句

這是沒有意義的,因為TestEmployee有一個薪水,它被傳入並發送到基類Employee因為TestEmployee派生自Employee 獎金是補償的一個單獨部分,將單獨存儲。 理想情況下,您將在Employee基類中有一個不同的構造函數,它允許傳遞TestEmployee可以訪問的salarybonus

正如其他人所說,您無法按照自己嘗試的方式完全按照自己的意願行事。 但是,您可以做的是稍微不同地設計您的類,以便您可以實現相同的目標。

class Employee{
   double salary;
   Employee(double salary){
      this.salary = salary;
   }
}
class TestEmployee extends Employee{
   TestEmployee(double salary, double bonus){
        super(salary);
        this.bonus=bonus;
   }

   double bonus;
}

然后,如果你想要一個默認的 TestEmployee 構造函數,你可以這樣做:

TestEmployee() {
  this(1000000,10000);
}

為了防止代碼重復,您可以定義一個非靜態方法,該方法為所有構造函數執行所有初始化塊。您可以在調用 super() 之后包含此方法以初始化您的對象。但缺點是..它可以從類中的任何其他方法調用。所以這不是一個好的設計模式

class TestEmployee extends Employee{

       double bonus;

       TestEmployee(){
            super(1000000);
            intialize(10000);
       }

       TestEmployee(double bonus){
          super(bonus);
           intialize(bonus);
       }
       private void intialize(double bonus)
       {
           this.salary = bonus;
       }
    }

你不能把這兩個調用放在同一個構造函數中,因為在調用父類時,它們都需要首先放在構造函數中。 當你有一個額外的參數時,你可以在同一個構造函數中使用 this 和 super 。 就像在這個例子中:

class TestEmployee extends Employee{
double: age;
   TestEmployee(double salary, double age){
        super(1000000);
        this.age=age;
   }
Or when you are using a Chaining Constructor, for example:
public class Employee{
String name;
double salary;
double age;
 public Employee()
    {
        this("James Bond", 34000);
    }

    public Employee(String n, double s)
    {
       this("Ana", 34000, 23);
    }
public Employee(String n, double s, double age)
    {
        name = n;
        salary = s;
        this.age=age;

    }

正如其他人所說,你為什么要這樣做。 這沒有道理。
您可以通過調用另一個構造函數來偽造它,該構造函數又調用其超類構造函數。 但是,如果調用另一個構造函數的唯一原因是傳遞到另一個超類構造函數而不是隱式調用的構造函數,那么幾乎可以肯定您的設計存在嚴重錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM