2.14 Calling Overridden Methods2.13 Method Overriding2 Java with Caffeine2.15 Shadowing Variables

2.14 Calling Overridden Methods

The method printInfo in Book shares a lot of functionality with the corresponding method of the superclass. It would be therefore good if the method in the subclass could invoke the method of the superclass. For this reason, Java has the pseudo-object super which refers to the current object (this) but considers it as an object of the superclass. We may then write

   class Book extends Article
   {
     String author;
     String publisher;
     String ISBN;
     ...
     void printInfo()
     {
       super.printInfo();
       System.out.print("This is a book written by " + author);
       System.out.print(" and published by " + publisher);
       System.out.println(" with ISBN number " + ISBN + ".");
     }
   }

The method printInfo in class Book invokes (with this object) the method printInfo of the superclass Article. In this fashion, functionality may be gradually extended starting with a simple general definition in the superclass that is appropriately refined in subclasses.

Any other method may use super to refer to a method of the superclass which was overridden by a definition in the current class. For instance, we may define

   class Book extends Article
   {
     ...
     void printInfo() { ... }
     ...
     void printArticleInfo() 
     {
       super.printInfo();
     }
   }

The program fragment

   Book book = new Book(...);
   book.printArticleInfo();

now invokes the method printInfo in class Article.


© Wolfgang Schreiner; February 3, 2005

2.14 Calling Overridden Methods2.13 Method Overriding2 Java with Caffeine2.15 Shadowing Variables