⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ex_5_4_1.java

📁 java思想编程与设计模块
💻 JAVA
字号:
/*
 *文件名:ex_5_4_1.java
 *说  明:继承机制举例
 */
import java.awt.*;

// 矩形类 --- Object类的直接子类
class Rect {
    // 成员变量
    // 左上角和右下角坐标
    public int x1, y1, x2, y2;
    // 构造方法 1
    public Rect(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    // 构造方法 2
    public Rect(int width, int height) { this(0, 0, width, height); }
    // 默认构造方法
    public Rect() { this(0, 0, 0, 0); }

    // 移动矩形方法
    public void move(int deltax, int deltay) {
        x1 += deltax; x2 += deltax;
        y1 += deltay; y2 += deltay;
    }

    // 测试某个点是否在矩形内
    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 {
    // 构造方法
    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;
    
    // 构造方法
    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) {
        //创建Rect对象
        Rect r1 = new Rect(1, 1, 4, 4);    
        Rect r2 = new Rect(2, 3, 5, 6);
        // 创建ColoredRect对象
        ColoredRect r3=new ColoredRect(2,3,5,6,Color.yellow,Color.black);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -