Google
 
Site navigation: [ Home | Theory | Java | Moodle courses | Resource wiki | About ]

Inheritance - a practical introduction

This is really an HL topic but some aspects of inheritance are useful to SL also.

'

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The call to super calls the Constructor in the parent Class (TextField).

 

 

 

isEmpty() is a method of IntegerTextField

 

 

 

as is getInteger()

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

See the exceptions page for more details on this technique.

 

 

 

 

 

 

 

 

 

 

 

 

 

These simply call the corresponding constructors of the TextField superclass.

 

 

 

 

 

 

 

 

 

 

super can also be used to access the methods of the parent class.

 

 

A null String instance is returned if the binary input value is not valid.

 

 

A private helper method of the class.

Check that a byte has 8 bits

 

 

 

 

Check each of the 8 bit positions in turn for a 1 or a 0.

Notice that the custom exception message can contain data too - here it says where the bad digit was found in the String.

 

Notice that the binary String must be of length 8 to work properly - this would appear as a pre-condition in a well-designed dossier application.

weight keeps track of the column weightings.

           10011101
        MSB          LSB

(Most and Least Significant Bits).

 

On this page: [ subclasses | extending the TextField | BinaryTextField ]

Creating a subclass

In this example we extend the capabilities of the TextField Class. So far we have been converting text strings in a text field to numeric form using the construct:

  int x = Integer.parseInt(someTextField.getText());

At times we have checked the TextField to see of there is any text, for example:

  String choice = someTextField.getText();
   if (choice.length != 0)
   {
     // process data
   }
   else
   {
     // some error
   }

We can create a TextField type that includes these additonal functions as methods while retaining all the functionality of the existing TextFiedl Class by extending it:

Let's call it IntegerTextField and build in the required methods:

/**
* a special type of text field for handling integers
*
* @author Mr J
* @version 20040220
*/

public class IntegerTextField extends java.awt.TextField
{

   // we don't actually need any extra data members for this class
   // the constructors can be extended from the superclass

   public IntegerTextField(int n)
   {
     super(n);
   }
   public IntegerTextField(String s)
   {
     super(s);
   }

   /**
   * Method to return status of the TextField
   *
   * @return true if the TextField has no text in it
   */

   public boolean isEmpty()
   {
     // Get the String in the field and test it for length
     return (super.getText().length() == 0);
   }

   /**
   * Method to return contents of the field as an int
   * @return the integer
   */

   public int getInteger()
   {
     return Integer.parseInt(super.getText().trim());
   }
}

This Class can now be used in an Applet (or other application):

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/**
* Adds two numbers together - uses a the new IntegerTextField Class
*
* @author Mr J
* @version 20040220
*/

public class AddTwoAgain extends Applet implements ActionListener
{
   private IntegerTextField number1 = new IntegerTextField(20);
   private IntegerTextField number2 = new IntegerTextField(20);
   private Button pressMe = new Button("Add");
   private Label greeting = new Label("The answer");

   /**
   * Add objects to the Applet
   */

   public void init()
   {
     add(number1);
     add(number2);
     add(greeting);
     add(pressMe);
     pressMe.addActionListener(this);
   }

   /**
   * When the button is pressed, do the calculation
   *
   * @param e carries details about the event that occurred
   */

   public void actionPerformed(ActionEvent e)
   {
     
// assume user types in whole numbers only
     if ( number1.isEmpty() || number2.isEmpty() )
     {
       greeting.setText("Please enter two numbers");
     }
     else
     {
       greeting.setText( "Answer: " + ( number1.getInteger()
                                    +   number2.getInteger() ) );
     }
   }
}

There may not be a huge apparent benefit for re-writing the AddTwo Applet in this way but for more complex objects that are frequently re-used it saves time and is more reliable (test the Class once and re-use as many times as you want).

The next example shows that Exceptions and extended TextField's can be used together to validate data that needs to be input to an application.

Back to top

The BinaryTextField

In this example we are going to developa quiz to test the user's knowledge of decimal to binary conversion. The user will have to type in a binary number. The validation of input will be put into an a BinaryTextField Class which extends the awt.TextField Class.

First we build the exception Class:

/**
* Exceptions for a new BinaryTextField Example
* This is a way of creating customised error messages
*
* Class has 2 constructors which use the java.lang.exception package
*/


class BinaryTextFieldException extends Exception
{
   public BinaryTextFieldException()
   {
     super();
   }
   public BinaryTextFieldException(String s)
   {
     super(s);
   }
}

Now the BinaryTextField Class, first the constructors:

/**
* This class is used for unsigned binary numbers of 8 bits length
*/

class BinaryTextField extends java.awt.TextField
{

// Constructors (as for TextField)
  public BinaryTextField()
   {
     super();
   }
  public BinaryTextField(int columns)
   {
     super(columns);
   }
  public BinaryTextField(String text)
   {
     super(text);
   }
  public BinaryTextField(String text, int columns)
   {
     super(text, columns);
   }

Next, here are some methods that we will need to validate the input (for this exercise a binary number must have 8 bits and every digit must be either a 1 or a 0.

/**
* This method returns a valid binary String of 8 bits or passes up an exception
* @return java.lang.String
*/

public String binaryValue() throws BinaryTextFieldException
{
   // Use the TextField built-in method for getting the text
   String s = super.getText()
   if ( isBinary() ) // method to test if is valid binary string
  {
     return s;
   }
   else
   {
     return null; // return a null value on error
   }
}

/**
* This method tests the binary number to see if it is a valid
* 8-bit binary unsigned integer
*/

private boolean isBinary() throws BinaryTextFieldException
{
   boolean ok = true;
   String s = super.getText();

   if ( s.length() != 8 ) // byte must have 8 bits
   {
     // throw an exception with a custom error message
     ok = false;
     throw new BinaryTextFieldException("Bad byte length");
  }
   else
   {
     int pos = 0;
     char c;
     while ( (pos < 8) && (ok) )
     {
       c = s.charAt(pos);
       if ( (c != '0') && (c != '1') ) // each bit must be a 1 or a 0
       {
         ok = false;
         throw new BinaryTextFieldException("Bad digit " + c + " at " +
                                                                     (++pos));
       }
       pos++;
     }
    return (ok);
  }
   /**
   * This method converts the valid, unsigned binary String of 8 bits
   * in the TextField to an integer
   *
   * @return int
   */
   public int convert
()
   {
     int sum = 0;
     int weight = 1;
     String s = binaryValue(); // also checks that the String is valid
     // start at the LSB (right end of String)
     // if the digit is a 1, add it in to total

     for (int pos = 7; pos >= 0; pos--)
     {
       if ( s.charAt(pos) == '1' )
       {
         sum += weight;
       }
       weight *= 2; // next digit up is worth twice as much as this one
     }
     return(sum);
   }
}

Back to top

The next page shows the BinaryQuiz Applet which actually makes use of the Classes developed here.

Related: [ Java Home | previous:Exceptions| next:Binary Quiz Applet ]

A key feature of OOP languages is the ability to extend existing classes by giving them extra methods and properties.

Such classes have access to the functionality of the parent (or super) class.


 
The site is partly financed by advertising revenue, partly by online teaching activities and partly by donations. If you or your organisation feel these resouces have been useful to you, please consider a donation, $9.95 is suggested. Please report any issues with the site, such as broken links, via the feedback page, thanks.

Questions or problems related to this web site should be addressed to Richard Jones who asserts his right to be identified as the author and owner of these materials - unless otherwise indicated. Please feel free to use the material presented here and to create links to it for non-commercial purposes; an acknowledgement of the source is required by the Creative Commons licence. Use of materials from this site is conditional upon your having read the additional terms of use on the about page and the Creative Commons Licence. View privacy policy.

Creative Commons License


This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. © 2001 - 2009 Richard Jones, PO BOX 246, Cambridge, New Zealand;
This page was last modified: May 31, 2009