2.3 Superclasses and Subclasses2.2 Example2 Java with Caffeine2.4 Class Hierarchies

2.3 Superclasses and Subclasses

The envisioned software should provide a class Article which offers the common functionality of books and CDs:

   class Article
   {
     int number;
     String title;
     int price;

     Article (...) { ... }

     int getNumber() { ... }
     String getTitle() { ... }
     int getPrice() { ... }
  }

Books and CDs are now special cases of articles; they have the same fields and methods as articles but also provide additional fields and methods. A corresponding Java class Books for books is therefore the following one:

   class Book extends Article
   {
     String author;
     String publisher;
     String ISBN;

     Book(...) { ... }

     String getAuthor() { ... }
     String getPublisher() { ... }
     String getISBN() { ... }
   }

The clause extends means that Book is derived from Article, i.e., it inherits all fields and methods of Article as if they were declared locally within the class. We call Article the  superclass (or  parent class) of Book and Book its  subclass (or  child class).

In general, we have the following form of class declaration

   class Subclass extends Superclass
   {
     ...
   }

 

If the class implements one more interfaces, its declaration looks like

   class Subclass extends Superclass implements Interface, ...
   {
     ...
   }

Please note that while a Java class may implement multiple interfaces, it may only inherit from one superclass ( single inheritance).


© Wolfgang Schreiner; February 3, 2005

2.3 Superclasses and Subclasses2.2 Example2 Java with Caffeine2.4 Class Hierarchies