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

// In the previous code we have used services from both MouseAdapter and 
// JFrame.  Since we could only extend from JFrame, we created an object
// of class MouseAdapter and passed it to the listener of mouse events
// via butt.addMouseListener(ma).  But we can flip the roles: that is,
// we can extend from MouseAdapter and create a JFrame object.  Now
// we say butt.addMouseListener(this) because A31 objects are also 
// MouseListener objects via extending from MouseAdapter.  But we also
// say j.add("North",butt) instead of add("North",butt) because A31
// objects are not JFrame objects - instead they use the services of
// a JFrame through an object j created in the constructor of A31.
// In addition, we cannot say w.setSize() or w.setVisible() because w is
// not of type JFrame.  So we use j.setSize() and j.setVisible() in the
// constructor of A31 instead.  Finally, mousePressed() and mouseReleased()
// override methods of the same name in the MouseAdapter class (which 
// A31 subclasses).
class A31 extends MouseAdapter {
   JFrame j = new JFrame();
   JButton butt = new JButton("Yikes");
   JTextArea text = new JTextArea();

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

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

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

public class A3 extends Applet {
   public void init () {
      A31 w = new A31();
   }
}