Reusable Objects

A feature of Java that makes it an extremely useful language is the ability to reuse objects. This and the following web pages illustrate a simple Card object and a variety of ways in which it can be used. The Card object simply displays a text string against a background of a specified color; when a user clicks the mouse on the Card, a different text string is displayed against a possibly different background color. Click on this applet a few times to see how this simple Card object behaves.

The constructor for Card has the following structure:

Card(String s1, Color c1, String s2, Color c2)
	s1 = text string displayed when Card is first displayed
	c1 = original background color for Card
	s2 = text string displayed after Card is clicked
	c2 = background color after Card is clicked
   

Below is the entire Java code for the applet displayed above.

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

public class CardTest extends Applet
{	
	public void init() {
		setLayout(new GridLayout(1,1));
		add(new Card("front",Color.blue,"reverse",Color.red));
		repaint();
	}
}
   

Note that we are able to use the Card object without knowing anything about how it accomplishes its task.

Next Card example