继承—矩形

 1 /*
 2 编写一个矩形类Rect,包含:
 3 两个protected属性:矩形的宽width;矩形的高height。
 4 两个构造方法:
 5 1.一个带有两个参数的构造方法,用于将width和height属性初化;
 6 2.一个不带参数的构造方法,将矩形初始化为宽和高都为10。
 7 两个方法:
 8 求矩形面积的方法area()
 9 求矩形周长的方法perimeter()
10 */
11 package C;
12 
13 public class Rect {
14 
15     protected double width;
16     protected double height;
17 
18     public Rect(double width, double height) {
19         this.width = width;
20         this.height = height;
21     }
22 
23     public Rect() {
24         width = 10;
25         height = 10;
26     }
27 
28     public double area() {
29         return width * height;
30     }
31 
32     public double perimeter() {
33         return (width + height) * 2;
34     }
35 }
 1 /*
 2 通过继承Rect类编写一个具有确定位置的矩形类PlainRect,其确定位置用
 3 矩形的左上角坐标来标识,包含:
 4 添加两个属性:矩形左上角坐标startX和startY。
 5 两个构造方法:
 6 带4个参数的构造方法,用于对startX、startY、width和height属性
 7 初始化;
 8 不带参数的构造方法,将矩形初始化为左上角坐标、长和宽都为0
 9 的矩形;
10 添加一个方法:
11 判断某个点是否在矩形内部的方法isInside(double x,double y)。如在矩
12 形内,返回true, 否则,返回false。
13 */
14 package C;
15 
16 public class PlainRect extends Rect {
17 
18     public double startX;
19     public double startY;
20 
21     public PlainRect(double startX, double startY, double w, double h) {
22         this.startX = startX;
23         this.startY = startY;
24         width = w;
25         height = h;
26     }
27 
28     public PlainRect() {
29         startX = 0;
30         startY = 0;
31         width = 0;
32         height = 0;
33     }
34 
35     public boolean isInside(double x, double y) {
36         if (x >= startX && x <= (startX + width) && y >= startY && y <= (startY + height)) {
37             return true;
38         } else {
39             return false;
40         }
41     }
42     
43     
44 }
 1 /*
 2 编写PlainRect类的测试程序
 3 创建一个左上角坐标为(10,10),长为20,宽为10的矩形对象;
 4 计算并打印输出矩形的面积和周长;
 5 判断点(25.5,13)是否在矩形内,并打印输出相关信息。
 6 */
 7 package C;
 8 
 9 public class Text_Rect {
10 
11     public static void main(String[] args) {
12 
13         PlainRect jx = new PlainRect(10, 10, 10, 20);
14         System.out.println("矩形的周长=" + jx.perimeter());
15         System.out.println("矩形的面积=" + jx.area());
16 
17         if (jx.isInside(25.5, 13)) {
18             System.out.println("点(25.5,13)在矩形内部。");
19         } else {
20             System.out.println("点(25,5,13)不在矩形内部。");
21         }
22 
23     }
24 
25 }

运行结果:

posted @ 2016-05-23 14:01  唐枫  阅读(343)  评论(0编辑  收藏  举报