4

I am having problems with some course work i'm trying to finish off and any help would be appreciated!

I have 3 types of accounts which extend an abstract type "Account".. [CurrentAccount, StaffAccount and MortgageAccount].

I am trying to read in some data from file and create account objects along with user objects to add to hashmaps stored within the program.

When I create account objects I use a temporary variable of type Account and define its subtype dependant on the data read in.

for example:

Account temp=null;

if(data[i].equalsIgnoreCase("mortgage"){
    temp= new MortgageAccount;
}

Problem is when I try to call a method belonging to type MortgageAccount..

Do I need a temp variable of each type, StaffAccount MortgageAccount and CurrentAccount and use them coresspondingly in order to use their methods?

Thanks in advance!

4

4 回答 4

9

如果您的所有帐户对象都具有相同的接口,这意味着它们声明了相同的方法并且它们仅在实现方式上有所不同,那么您不需要每种类型的变量。

但是,如果要调用特定于子类型的方法,则需要该类型的变量,或者需要转换引用才能调用该方法。

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();

}
于 2011-11-21T05:25:46.700 回答
7

这取决于。如果父类Account在 中重写了一个方法MortgageAccount,那么当您调用该方法时,您将获得该MortgageAccount版本。如果该方法仅存在于 中MortgageAccount,那么您需要强制转换变量来调用该方法。

于 2011-11-21T05:12:33.460 回答
4

这是概念Dynamic method dispatch

如果您使用基类的引用变量并创建派生类的对象,那么您只能访问在基类中定义或至少声明的方法,并且在派生类中覆盖它们。

要调用派生类的对象,您需要派生类的引用变量。

于 2011-11-21T05:11:04.163 回答
4

你所需要的只是一个类型的对象MortgageAccount来调用它的方法。您的对象temp是类型MortgageAccount,因此您可以只调用该对象上MortageAccountAccount方法。不需要铸造。

于 2011-11-21T05:08:59.773 回答