Article

Object Oriented Concepts in Java - Part 1

Page: 1 2 3 4 5 6 7 Next

Inheritance

One of the strengths of object-oriented programming is inheritance. This feature allows you to create a new class that is based on an old class. Let's say your program also needed to keep track of coconut trees, so you would need a new class called CoconutTree that kept track of the number of coconuts in each tree. You could write the CoconutTree class from scratch, copying all the code from the Tree class that is responsible for tracking the height of the tree and allowing the tree to grow, but for more complex classes that could involve a lot of duplicated code. What would happen if you later decided that you wanted your Trees to have non-integer heights (like 1.5 meters)? You would have to adjust the code in both classes!

Inheritance allows you to define your CoconutTree class as a subclass of the Tree class, such that it inherits the properties and methods of that class in addition to its own. To see what I mean, here's the code for CoconutTree:

1  /**    
2   * CoconutTree.java    
3   * A more complex kind of tree.    
4   */    
5    
6  class CoconutTree extends Tree {    
7    public int numNuts = 0; // Number of coconuts    
8    
9    public void growNut() {    
10     numNuts = numNuts + 1;    
11   }    
12    
13   public void pickNut() {    
14     numNuts = numNuts – 1;    
15   }    
16 }

The words extends Tree on line 6 endow the CoconutTree class with a height property and a grow method in addition to the numNuts property and the growNut and pickNut methods that are declared explicitly for the class.

By building up a hierarchical structure of classes with multiple levels of inheritance, you can create powerful models of complex Objects with little or no duplication of code (which makes for less typing and easy maintenance). We'll see more examples of the power of inheritance later in this series.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links