Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling child method, when cast to parent type in java

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!

like image 926
krex Avatar asked Nov 29 '22 09:11

krex


1 Answers

If all your account objects have the same interface, meaning they declare the same methods and they only differ in how they are implemented then you do not need a variable for each type.

However, if you want to call a method that is specific to the sub-type then you would need a variable of that type, or you would need to cast the reference before you would be able to call the method.

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

}
like image 67
Eric Rosenberg Avatar answered Dec 05 '22 15:12

Eric Rosenberg