Java Reference
In-Depth Information
Example 2•4: ColoredRect.java
package com.davidflanagan.examples.classes;
import java.awt.*;
/**
* This class subclasses DrawableRect and adds colors to the rectangle it draws
**/
public class ColoredRect extends DrawableRect {
// These are new fields defined by this class.
// x1, y1, x2, and y2 are inherited from our super-superclass, Rect.
protected Color border, fill;
/**
* This constructor uses super() to invoke the superclass constructor, and
* also does some initialization of its own.
**/
public ColoredRect(int x1, int y1, int x2, int y2,
Color border, Color fill)
{
super(x1, y1, x2, y2);
this.border = border;
this.fill = fill;
}
/**
* This method overrides the draw() method of our superclass so that it
* can make use of the colors that have been specified.
**/
public void draw(Graphics g) {
g.setColor(fill);
g.fillRect(x1, y1, (x2-x1), (y2-y1));
g.setColor(border);
g.drawRect(x1, y1, (x2-x1), (y2-y1));
}
}
Complex Numbers
Example 2-5 shows the definition of a class that represents complex numbers. You
may recall from algebra class that a complex number is the sum of a real number
and an imaginary number. The imaginary number i is the square root of -1. This
ComplexNumber class defines two double fields, which represent the real and imagi-
nary parts of the number. These fields are declared private , which means they
can be used only within the body of the class; they are inaccessible outside the
class. Because the fields are inaccessible, the class defines two accessor methods,
real() and imaginary() , that simply return their values. This technique of making
fields private and defining accessor methods is called encapsulation . Encapsula-
tion hides the implementation of a class from its users, which means that you can
change the implementation without it affecting the users.
Notice that the ComplexNumber class doesn't define any methods, other than the
constructor, that set the values of its fields. Once a ComplexNumber object is cre-
ated, the number it represents can never be changed. This property is known as
immutability ; it is sometimes useful to design objects that are immutable like this.
Search WWH ::




Custom Search