所以我有一个关于如何在JAVA中创建子类实例的问题。是的,这是年级的家庭作业,我已经完全实现了一个具有默认值的主类和一个 Account 类的参数化构造函数。
我创建了两个子类:储蓄和支票。作业书中唯一的规定是支票账户的取款不能超过 overdraw 限额,而储蓄账户根本不能 overdraw 。
class Checking extends Account{
double overdraftLimit = -100;
public void withdraw(double w) {
if (balance - w < overdraftLimit)
System.out.println("You can't overdraft more than $100.");
else
balance = balance - w;
}
}
class Savings extends Account{
double overdraftLimit = 0;
public void withdraw (double w) {
if (balance - w < overdraftLimit)
System.out.println("You don't have enough money, fool.");
else
balance = balance - w;
}
}
我的问题是,我不确定如何创建特定子类的实例,Savings
或Checking
。有人对我有建议吗?在我的父类 Account
中,我已经有一个 withdraw ( double w )
方法,例如 balance -= w
。我已经在每个子类中重写了withdraw方法。我的代码编译并运行,但在问题中,我被指示编写一个测试程序,该程序创建 Account
、Savings
、Checking
类型的对象并调用其 toString()
方法。我已经和我的导师谈过了,这个问题在打印之前没有完全完成,因为没有关于 Checking
帐户允许的 overdraw 限额的说明。
也没有提及我应该调用的 toString()
方法,因此我跳过了这部分作业。
最佳答案
如果我正确理解您的问题(并随时澄清),您需要为每个类创建一个构造函数:
public Checking(){
super();
//other initialization
}
public Savings(){
super();
//other initialization
}
并使用关键字new
从您的main
调用它们:
Savings mySavings = new Savings();
Checking myChecking = new Checking();
Account myAccount = new Account();
关于java - Account子类对象创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23283954/