kre*_*rex 3 java polymorphism class-hierarchy
我正在尝试完成一些课程工作的问题,任何帮助将不胜感激!
我有3种类型的帐户,它们扩展了抽象类型"帐户".. [CurrentAccount,StaffAccount和MortgageAccount].
我试图从文件中读取一些数据并创建帐户对象以及用户对象以添加到程序中存储的哈希映射.
当我创建帐户对象时,我使用Account类型的临时变量,并根据读入的数据定义其子类型.
例如:
Account temp=null;
if(data[i].equalsIgnoreCase("mortgage"){
temp= new MortgageAccount;
}
Run Code Online (Sandbox Code Playgroud)
问题是当我尝试调用属于MortgageAccount类型的方法时.
我是否需要每种类型的临时变量,StaffAccount MortgageAccount和CurrentAccount并使用它们coresspondingly才能使用他们的方法?
提前致谢!
这取决于.如果父类Account有一个方法被覆盖MortgageAccount,那么当你调用该方法时,你将获得该MortgageAccount版本.如果该方法仅存在MortgageAccount,则需要转换变量以调用该方法.
如果所有帐户对象都具有相同的接口,这意味着它们声明了相同的方法,并且它们的实现方式不同,那么每种类型都不需要变量.
但是,如果要调用特定于子类型的方法,则需要该类型的变量,或者您需要在能够调用该方法之前强制转换该引用.
class A{
public void sayHi(){ "Hi from A"; }
}
class B extends A{
public void sayHi(){ "Hi from B";
public void sayGoodBye(){ "Bye from B"; }
}
main(){
A a = new B();
//Works because the sayHi() method is declared in A and overridden in B. In this case
//the B version will execute, but it can be called even if the variable is declared to
//be type 'A' because sayHi() is part of type A's API and all subTypes will have
//that method
a.sayHi();
//Compile error because 'a' is declared to be of type 'A' which doesn't have the
//sayGoodBye method as part of its API
a.sayGoodBye();
// Works as long as the object pointed to by the a variable is an instanceof B. This is
// because the cast explicitly tells the compiler it is a 'B' instance
((B)a).sayGoodBye();
}
Run Code Online (Sandbox Code Playgroud)