Account acct2 = new SavingsAccount (name);
acct2.calculateBalance();
This is because although you have an object of SavingsAccount
you are using refrence variable of type Account
so you can access only those methods that are there in Account
class.
And you don't have calculateBalance()
method in your Account
class.
That's why you are not able to access it and compiler complains that it cannot find a method named calculateBalance
as it sees that reference type is Account
and there is no such method inside Account
class.
If you want to use that method then change reference type to SavingsAccount
:
SavingsAccount acct2 = new SavingsAccount (name);
Or you can explicitly cast it when accessing that method
((SavingsAccount) acct2).calculateBalance();
but be alert that it can throw ClassCastException
if acct2
object is actually not an object of SavingsAccount
UPDATE:
But
remember that at runtime, Java uses virtual method invocation to dynamically
select the actual version of the method that will run, based on the actual instance.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…