Polymorphism

  • Means “many forms”
  • allows to initialize the subclass using the superclass

Example

BankAccount myAcct = new SavingsAccount(1, 100, 0.01);

Interchanging the classes will result in an error.

Note

  • The subclass can only access the service methods of the superclass
  • If the subclass has the same method(same name i think) from the superclass, the method of the subclass will be used
  • To use the subclass methods, the subclass must be instanced using its own type
BankAccount myAcct = new SavingsAccount(3, 25500000, 0.1);
myAccount.addInterest(); // will cause an error, since method is defined in the subclass.
SavingsAccount mySavings = (SavingsAccount) myAcct;
mySavings.addInterest(); // will work since correct type is used.