2.11 Generic Methods2.10 Static Types and Dynamic Types2 Java with Caffeine2.12 The Object Class

2.11 Generic Methods

Since objects variables may have multiple dynamic types, we can also write  generic methods that operate in the same way on objects of these types.

For instance, we may write a method that prints the information available on an article:

   static void printInfo(Article a)
   {
     int number = a.getNumber();
     String title = a.getTitle();
     int price = a.getPrice();
     System.out.print("Article '" + title);
     System.out.print( "' (" + number + ") costs ");
     System.out.println(price/100 + "." + price%100 + " Euro.");
   }

We may call this method for both books and CDs:

   Book book = new Book(...);
   CD cd = new CD(...);
   printInfo(book);
   printInfo(cd);

Since Book and CD are both subclasses of Article, it is legal to call printInfo with a Book object respectively with a CD object as an argument. The parameter a of static type Article once receives the dynamic type Book and once the dynamic type CD.

To have such generic methods that operate on objects of different types is one of the main advantages of an object-oriented language like Java.


© Wolfgang Schreiner; February 3, 2005

2.11 Generic Methods2.10 Static Types and Dynamic Types2 Java with Caffeine2.12 The Object Class