修復 Java 無法例項化型別錯誤

Haider Ali 2023年10月12日
修復 Java 無法例項化型別錯誤

今天,我們將學習如何修復 Java 中的無法例項化型別錯誤的錯誤。

當你嘗試建立抽象類的例項時,會發生此類錯誤。讓我們學習一下 Java 中的抽象類。

修復 Java 中的無法例項化型別錯誤

當我們需要在其所有元件之間提供一些通用功能時,我們通常使用抽象類。你將能夠部分實現你的課程。

你將能夠生成所有子類都能夠覆蓋或實現的功能。但是,你不能例項化抽象類。

看下面的程式碼:

abstract class Account { // abstract class Cannot Be initiated...
  private int amount;
  Account() {
    // constructor............
  }
  public void withDraw(int amount) {
    this.amount = this.amount - amount;
  }
}

上面的抽象類 Account 不能被例項化。這意味著你不能編寫以下程式碼。

Account acc = new Account(); // Abstract Cannot Intialized......

那麼,有什麼解決辦法呢?你可以建立此抽象類的具體/子類併為其建立例項。

例如,有很多型別的帳戶。它們可以是儲蓄、業務、借記卡等等。

但是,它們都是真實的帳戶,這是它們的共同點。這就是我們使用抽象方法和類的原因。

看看下面的程式碼。

class BusinessAccount extends Account {
  private int Bonus;
  public void AwardBonus(int amount) {
    this.Bonus = Bonus + amount;
  }
}

BusinessAccount 類是抽象 Account 類的具體子類。你可以建立此類的例項並完成工作。

BusinessAccount bb = new BusinessAccount();
// Bussiness Account Can Be intiated Because there is concreate defination..........

所以,結論是你不能例項化抽象類;相反,你可以建立它的子類並例項化它以實現相同的功能。

以下是可以在你的計算機上執行的完整程式碼。

abstract class Account { // abstract class Cannot Be intiated...
  private int amount;
  Account() {
    // constructor............
  }
  public void withDraw(int amount) {
    this.amount = this.amount - amount;
  }
}
class BusinessAccount extends Account {
  private int Bonus;
  public void AwardBonus(int amount) {
    this.Bonus = Bonus + amount;
  }
}
public class Main {
  public static void main(String[] args) {
    // Account acc = new Account(); // Abstract Cannot Intialized......
    BusinessAccount bb = new BusinessAccount();
    // Bussiness Account Can Be intiated Because there is concreate defination..........
  }
}

要了解有關抽象類的更多資訊,請單擊此處

作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相關文章 - Java Error