Chapter 7: Polymorphism and Interfaces Concepts

Classwork: Constructors and Methods behavior diagrams.

Polymorphism and Interfaces:

In Java, all instance methods are polymorphic. The same computation works for objects of many shapes, and adapts itself to the nature of the objects.

Polymorphism denotes the principle that behavior can vary depending on the actual type of an object.

When the virtual machine calls an instance method, it locates the method of the implicit parameter’s class. This is called dynamic method lookup.

Dynamic method lookup enables a programming technique called polymorphism.

There is an important difference between polymorphism and overloading. The compiler picks an overloaded method when translating the program, before the program ever runs. This method selection is called early binding.

Interfaces: when selecting the appropriate getMeasure method in a call x.getMeasure(), the compiler does not make any decision when translating the method as mentioned above. The program has to run before anyone can know what is stored in x. Therefore, the virtual machine, and not the compiler, selects the appropriate method. This method selection is called late binding.

Using a polymorphic reference as the formal parameter to a method is a powerful technique. It allows the method to control the types of parameters passed into it, yet gives it the flexibility to accept arguments of various types.

Looking again at the driver for the DataSet of Measurable objects, we have seen this code:

public static void main(String[] args)
   {
      DataSet bankData = new DataSet();
      
      bankData.add(new BankAccount(3000));
      bankData.add(new BankAccount(10000));
      bankData.add(new BankAccount(2000));

      System.out.println("Average balance = " + bankData.getAverage());
      
      Measurable max = bankData.getMaximum();
      System.out.println("Highest balance = " + max.getMeasure());
      //System.out.println("Get bank balance = " + max.getBalance()); 
      // ERROR since "max" is not an object of BankAccount
      BankAccount maxAccount = (BankAccount) max; 
      // casting from interfaces to classes
      // max ---> maxAccount ( object of BankAccount )
      System.out.println("Get bank balance = " + maxAccount.getBalance());
      // NO ERROR
      ....
}

To protect against bad casts, you can use the instanceof operator.

Here is a good example:

if ( max instaceof BankAccount )
   {
      BankAccount maxAccount = (BankAccount) max; 
      System.out.println("Get bank balance = " + maxAccount.getBalance());
    }

Homework:
Check edmodo.com