HOWTO · Java
修复 Java 无法实例化类型错误
如何修复无法实例化 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..........
}
}
要了解有关抽象类的更多信息,请单击此处。