CSE143 Inheritance Examples handout #27
Class StutterList.java
----------------------
// Variation of ArrayList that adds values twice with the appending add.
import java.util.*;
public class StutterList extends ArrayList {
public boolean add(E value) {
super.add(value);
super.add(value);
return true;
}
}
Class CustomFrame.java
----------------------
// Simple example of inheritance to change the behavior of a Frame. This uses
// deprecated methods, so it is not considered an example of good Java code.
import java.awt.*;
public class CustomFrame extends Frame {
private int oldX, oldY;
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 50);
g.setColor(Color.YELLOW);
g.fillRect(50, 100, 25, 25);
}
public boolean mouseDown(Event e, int x, int y) {
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.fillOval(x - 5, y - 5, 10, 10);
oldX = x;
oldY = y;
return true;
}
public boolean mouseDrag(Event e, int x, int y) {
Graphics g = getGraphics();
g.setColor(Color.RED);
g.drawLine(oldX, oldY, x, y);
oldX = x;
oldY = y;
return true;
}
}
Class DrawFrame.java
--------------------
// Short program that draws a custom frame and sets some of its properties.
import java.awt.*;
public class DrawFrame {
public static void main(String[] args) {
Frame f = new CustomFrame();
f.setSize(400, 400);
f.setTitle("What fun!!");
f.setBackground(Color.CYAN);
f.setVisible(true);
}
}
Class MyPoint.java
------------------
// Stuart Reges
// 11/27/06
//
// Variation of Point that keeps track of how many times each point has been
// translated and that provides a getTranslateCount method.
import java.awt.*;
public class MyPoint extends Point {
private int count;
public MyPoint() {
this(0, 0);
}
public MyPoint(int x, int y) {
super(x, y);
count = 0;
}
public void translate(int dx, int dy) {
count++;
super.translate(dx, dy);
}
public int getTranslateCount() {
return count;
}
}
Class PointTest.java
--------------------
// Stuart Reges
// 11/27/06
//
// Class that demonstrates simple use of the MyPoint class.
public class PointTest {
public static void main(String[] args) {
MyPoint p = new MyPoint(13, 42);
p.translate(3, 14);
p.translate(72, 4);
p.translate(-8, 9);
System.out.println("Translate count = " + p.getTranslateCount());
}
}
Output of PointTest
-------------------
Translate count = 3