这是(删节的)父类(super class):
public class Account
{
private double bal; //The current balance
private int accnum; //The account number
public Account(int a)
{
bal=0.0;
accnum=a;
}
}
子类:
public class SavingsAccount extends Account{
private static final double INTEREST_RATE = 5; // Interest amount for savings account
public SavingsAccount(int a) {
super(a);
}
public void addInterest(){
double interest = getBalance()/100*INTEREST_RATE;
deposit(interest);
}
}
主要代码:
public class AccountMain {
public static void main(String[] args) {
// Declare Variables
Account myAccount = new SavingsAccount(500);
// Do stuff
myAccount.deposit(1000);
System.out.println(myAccount.toString());
((SavingsAccount) myAccount).addInterest();
System.out.println(myAccount.toString());
}
}
当 myAccount 已声明为 SavingsAccount 时,为什么我必须将其转换为 SavingsAccount?
我读到的所有内容都意味着通过将新对象声明为子类应该使所有父类(super class)和子类方法都可用。我觉得我错过了一些东西,但又找不到什么。
最佳答案
Why am I having to cast myAccount as a SavingsAccount when it's been declared as a SavingsAccount?
这是您的变量声明部分:
Account myAccount;
这就是编译器理解变量类型的方式。
这是作业部分:
myAccount = new SavingsAccount(500);
您可以在此处为变量分配特定的对象引用。请注意,它不会也不能更改声明的类型。
因此您可以看到 myAccount 变量绝对没有被声明为 SavingsAccount 类型变量。它被声明为一个 Account 类型变量,并被分配了一个 SavingsAccount 类型对象。您也可以稍后更改对另一个 Account 类型对象的赋值,因此为了类型安全,如果您想将变量用作更具体的类型,编译器将要求您强制转换该变量。
关于java - 子类对象需要类型转换为子类才能访问子类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586152/