2.13 Method Overriding2.12 The Object Class2 Java with Caffeine2.14 Calling Overridden Methods

2.13 Method Overriding

We can make the static method printInfo presented above also a dynamic method of class Article:

   class Article
   {
     int number;
     String title;
     int price;
     ...
     void printInfo()
     {
       System.out.print("Article '" + title);
       System.out.print( "' (" + number + ") costs ");
       System.out.println(price/100 + "." + price%100 + " Euro.");
     }
    }

This method is inherited by Book and CD such that we may print books and CDs as follows:

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

However, this is actually not what we want. A book has more information than stored in class Article and we would like to have this additional information printed as well. For this reason, Java gives the possibility to  override a methods declared in a superclass by a declaration of the same name in a subclass. For instance, we may define

   class Book extends Article
   {
     String author;
     String publisher;
     String ISBN;
     ...
     void printInfo()
     {
       System.out.print("Article '" + title);
       System.out.print( "' (" + number + ") costs ");
       System.out.println(price/100 + "." + price%100 + " Euro.");
       System.out.print("This is a book written by " + author);
       System.out.print(" and published by " + publisher);
       System.out.println(" with ISBN number " + ISBN + ".");
     }
   }

When we now write

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

it is the printInfo method of class Book which is called and not the corresponding method of class Article.


© Wolfgang Schreiner; February 3, 2005

2.13 Method Overriding2.12 The Object Class2 Java with Caffeine2.14 Calling Overridden Methods