?? ex_5_4_1.java
字號:
/*
*文件名:ex_5_4_1.java
*說 明:繼承機制舉例
*/
import java.awt.*;
// 矩形類 --- Object類的直接子類
class Rect {
// 成員變量
// 左上角和右下角坐標
public int x1, y1, x2, y2;
// 構(gòu)造方法 1
public Rect(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
// 構(gòu)造方法 2
public Rect(int width, int height) { this(0, 0, width, height); }
// 默認構(gòu)造方法
public Rect() { this(0, 0, 0, 0); }
// 移動矩形方法
public void move(int deltax, int deltay) {
x1 += deltax; x2 += deltax;
y1 += deltay; y2 += deltay;
}
// 測試某個點是否在矩形內(nèi)
public boolean isInside(int x, int y) {
return ((x >= x1)&& (x <= x2)&& (y >= y1)&& (y <= y2));
}
// 返回和另一個矩形的并集
public Rect union(Rect r) {
return new Rect((this.x1 < r.x1) ? this.x1 : r.x1,
(this.y1 < r.y1) ? this.y1 : r.y1,
(this.x2 > r.x2) ? this.x2 : r.x2,
(this.y2 > r.y2) ? this.y2 : r.y2);
}
// 返回和另一個矩形的交集
public Rect intersection(Rect r) {
Rect result = new Rect((this.x1 > r.x1) ? this.x1 : r.x1,
(this.y1 > r.y1) ? this.y1 : r.y1,
(this.x2 < r.x2) ? this.x2 : r.x2,
(this.y2 < r.y2) ? this.y2 : r.y2);
if (result.x1 > result.x2) { result.x1 = result.x2 = 0; }
if (result.y1 > result.y2) { result.y1 = result.y2 = 0; }
return result;
}
// 重載toString方法
public String toString() {
return "[" + x1 + "," + y1 + "; " + x2 + "," + y2 + "]";
}
}
// RrawableRect類,是Rect類的直接子類
class DrawableRect extends Rect {
// 構(gòu)造方法
public DrawableRect(int x1, int y1, int x2, int y2) { super(x1,y1,x2,y2); }
// RrawableRect類的新引入的方法
public void draw(java.awt.Graphics g) {
g.drawRect(x1, y1, (x2 - x1), (y2-y1));
}
}
// ColoredRect類,是DrawableRect的直接子類
class ColoredRect extends DrawableRect {
// 該類中新引入的成員變量
protected Color border, fill;
// 構(gòu)造方法
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;
}
// 重載draw方法
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));
}
}
//主類,用于測試
public class ex_5_4_1 {
public static void main(String[] args) {
//創(chuàng)建Rect對象
Rect r1 = new Rect(1, 1, 4, 4);
Rect r2 = new Rect(2, 3, 5, 6);
// 創(chuàng)建ColoredRect對象
ColoredRect r3=new ColoredRect(2,3,5,6,Color.yellow,Color.black);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -