INHERITANCE

bullet

Inheritance is extending the capabilities and functionality of a class

bullet

Inheritance allows you to build a hierarchy of classes, with parents (called superclasses) and children (called subclasses)

bullet

A superclass has one or more extensions - subclasses that are built upon the superclass

bullet

All classes in Java are subclasses of java.lang.Object

bullet

Once a superclass is defined, use the extends keyword to define a subclass.

bullet

Example - the Box superclass --

public class Box
{
   private boolean open;    // member variables
   private String content;

   public Box (String content) // constructor
   {
    open = true;
    this.content = content;
   }

   public void setOpen(boolean open)
   {
    this.open = open;
   }

    // more ... see p. 133

}

bullet

The LockableBox subclass --

public class LockableBox extends Box
{
private String password;
private boolean locked;
}

bullet

LockableBox objects have the member variables and methodsfrom Box as well as it's own member variables and methods

bullet

Use the super keyword to reference methods and members from the superclass --

bullet

public LockableBox (String password)
{
super("");
   //call to Box's constructor
this.password = password;
   //initialize LockableBox's password member var
super.setOpen(true);
   //initialize LockableBox's open member var
   //(which was inherited from Box ) to true
   //using Box's setOpen method

}

bullet

Overriding Methods -
When the functionality of the superclass' methods isn't quite right for the subclass

bullet

Example - consider the setOpen method -

bullet

for a Box object, merely pass the open state:

bullet

public void setOpen(boolean open)
{
setOpen(open);
}

bullet

for a LockableBox object, we should test if the box is locked if we're trying to open it:

public void setOpen (boolean open)
{
if (this.locked && open == true)
// if it's locked & you're trying to open it
   {
    MessageBox.show("The box is locked - "+
    "You should unlock it first");
   }
else
   {
    super.setOpen(open);
   }
}

bullet

Download the LockableBox source code example - pay cloase attention to the definition of LockableBox.java and Box.java

wpeD.jpg (11509 bytes)

Last Updated by DrB on Wednesday, February 18, 2009