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.*;

// There is nothing magic about the MouseAdapter class.  We can create
// such a class ourselves.  All we need to do is implement the MouseListener
// interface and supply all the required  methods.
class OurOwnPersonalMouseAdapter implements MouseListener {
   public void mousePressed (MouseEvent evt) { }
   public void mouseReleased (MouseEvent evt) { }
   public void mouseExited (MouseEvent evt) { }
   public void mouseEntered (MouseEvent evt) { }   
   public void mouseClicked (MouseEvent evt) { }
}

// The change from the previous code is only that we are subclassing 
// OurOwnPersonalMouseAdapter class instead of the MouseAdapter class.
class A41 extends OurOwnPersonalMouseAdapter {
   JFrame j = new JFrame();
   JButton butt = new JButton("Yikes");
   JTextArea text = new JTextArea();

   public A41 () {
      j.setLayout(new BorderLayout());
      j.add("North",butt);
      j.add("Center",text);
      butt.addMouseListener(this);
      j.setSize(300,300);
      j.setVisible(true);
   }

   // Overriding methods of the OurOwnPersonalMouseAdapter class
   public void mousePressed(MouseEvent evt) {
      text.append("Mouse button pressed\n");
   }

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

public class A4 extends Applet {
   public void init () {
      A41 w = new A41();
   }
}