Objects and Classes in Java |
Let's do something a bit more fun and look at an applet,Spot
. With this applet, we show you how to subclass another class and implement an interface. The last section of this lesson, Using an Inner Class to Implement an Adapter, shows you two alternative implementations of this class, both of which use inner classes.Here's the
Spot
applet running. The applet displays a small spot when you click over the applet with the mouse:
And here's the source code for the applet:
Note: Because some old browsers don't support 1.1, the above applet is a 1.0 version (here is the 1.0 code; here's the 1.1 code). To run the 1.1 version of the applet, go toexample-1dot1/Spot.html
.Theimport java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Spot extends Applet implements MouseListener { private java.awt.Point clickPoint = null; private static final int RADIUS = 7; public void init() { addMouseListener(this); } public void paint(Graphics g) { g.drawRect(0, 0, getSize().width - 1, getSize().height - 1); if (clickPoint != null) g.fillOval(clickPoint.x - RADIUS, clickPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); } public void mousePressed(MouseEvent event) { clickPoint = event.getPoint(); repaint(); } public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }extends
clause indicates that theSpot
class is a subclass ofApplet
. The next section, Extending a Class, talks about this aspect ofSpot
. TheimplementsSpot
implements one interface namedMouseListener
. Read about this aspect of theSpot
class in Implementing an Interface later in this lesson.
Objects and Classes in Java |