Java が Cannot Instantiate the Type 問題を修正

Haider Ali 2023年10月12日
Java が Cannot Instantiate the Type 問題を修正

今日は、Java で Cannot Instantiate the Type というエラーを修正する方法を学びます。

このタイプのエラーは、抽象クラスのインスタンスを作成しようとしたときに発生します。Java の抽象クラスについて少し学びましょう。

Java の cannot instantiate the type エラーの修正

すべてのコンポーネントに共通の機能を提供する必要がある場合は、通常、抽象クラスを使用します。クラスを部分的に実装できるようになります。

すべてのサブクラスがオーバーライドまたは実装できる機能を生成できるようになります。ただし、抽象クラスをインスタンス化することはできません。

次のコードを見てください。

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