Some intuition on Java class hierarchies
Previous    Next    Home     Java Source    Package

// This sequence is intended to aid in understanding a few things about Java:
//  1. A component such as JButton can be used inside another component
//     such as JFrame regardless of whether JButton subclasses JFrame or
//     vice versa or neither subclasses the other
//  2. When a class implements an interface, say I, objects of that class
//     also are of type I.  This allows a class such as JButton, which 
//     provides a service (doing something when a button is pressed), to
//     listen to an object of any class (which is also of type I) and to
//     provide a callback to that object.
//  3. In Java we can inherit from at most one super class but we can
//     achieve the same power as in multiple inheritance by creating
//     an object of the class that will provide the needed service and
//     run methods of that class from that object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

// Here we implement MouseListener.  Then A11 objects also are MouseListener 
// objects.  Hence butt.addMouseListener(this) establishes a link for
// the superclass of JButton to communicate back to A11 objects via
// actionPerformed().  Only objects of type MouseListener are allowed to
// do this but any data type can also be made an object of type MouseListener
// by implementing the MouseListener interface.  Because the MouseListener
// interface requires implementing mouseExited(), mouseEntered(),
// and mouseClicked(), these methods have to appear here as doing nothing.
class A11 extends JFrame implements MouseListener {
   JButton butt = new JButton("Yikes");
   JTextArea text = new JTextArea();

   public A11 () {
      setLayout(new BorderLayout());

   public void mousePressed(MouseEvent evt) {
      text.append("Mouse button pressed\n");

   public void mouseReleased(MouseEvent evt) {
      text.append("Mouse button released\n");

   public void mouseExited(MouseEvent evt) {}
   public void mouseEntered(MouseEvent evt) {}   
   public void mouseClicked(MouseEvent evt) {}

public class A1 extends Applet {
   public void init () {
      A11 w = new A11();