You are on page 1of 2

Look

at the solution to the class exercise from the last lecture. In this exercise, we had a Drawable interface (shown below), and we created two classes, a Rectangle and a Triangle, that both implement this interface. We had an applet class, Picture, that created an array of Drawables. In its init() method, the Picture applet created two Triangle objects and one Rectangle object, and put them all in the array of Drawables. The paint() method of Picture then stepped through the array to draw all the items. See the java code for the solutions to the class exercise for details of these classes.

Programming II, First Semester 2011 Lecture 26 Notes More about Interfaces

In todays lesson, we extend the Drawable interface to create a new interface called ColoredDrawable. The ColoredDrawable interface specifies a new method, setColor(), that is meant to specify the color that the object should be drawn with. The setColor method takes as an argument, an object of type Color, which is a predefined class in Java. To use this class, we need to import java.awt.Color. For more information on the Color class, see http://docs.oracle.com/javase/6/docs/api/java/awt/Color.html

We chose to use the Color class as the argument to our setColor() method in the ColoredDrawable interface because the Graphics class (which is what the applet uses to paint itself) has a method called setColor that requires a Color object as an argument. Thus, if we have a Color object, we can use it to draw an item with a particular color. Note that because the ColoredDrawable interface extends the Drawable interface, any class that implements the ColoredDrawable interface must implement the drawWithText() and drawWithGraphics() methods of the Drawable interface, as well as the setColor() method of the ColoredDrawable interface. We create a class called ColoredRectangle1 that implements the ColoredDrawable interface. That is, it provides bodies for the drawWithText(), drawWithGraphics(), and setColor() methods. Note that the constructor of the ColoredRectangle1 class calls its setColor method to set its default color to red. It does this using the statement: setColor(Color.RED) Color.RED is a constant declared in the Color class. Below is a screenshot from the Java API page for the class Color:

Lastly, we modified the Picture applet to create an array that holds a Rectangle, a ColoredRectangle, and a Triangle. This is the result when the applet is run:

You might also like