package zhongqiuzuoye; //自己写的方法 public class Rect { public double width; public double height; Rect(double width,double height) //带有两个参数的构造方法,用于将width和height属性初化; { this.width=width; this.height=height; } Rect() //不带参数的构造方法,将矩形初始化为宽和高都为10。 { width=10; height=10; } double area() //求矩形面积的方法 { System.out.println("矩形的面积为:"+width*height); return width*height; } double perimeter() //求矩形周长的方法 { System.out.println("矩形的周长为:"+2*(width+height)); return 2*(width+height); } }
package zhongqiuzuoye; //上课修改后的方法
public class Rect { private double width; private double height; public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } Rect(double width,double height) //带有两个参数的构造方法,用于将width和height属性初化; { this.width=width; this.height=height; } Rect() //不带参数的构造方法,将矩形初始化为宽和高都为10。 { this.width=10; this.height=10; } double area() //求矩形面积的方法 { System.out.println("矩形的面积为:"+width*height); return width*height; } double perimeter() //求矩形周长的方法 { System.out.println("矩形的周长为:"+2*(width+height)); return 2*(width+height); } }
package zhongqiuzuoye; public class PlainRect extends Rect{ double startX; double startY; PlainRect(double startX,double startY,double width,double height) //带4个参数的构造方法,用于对startX、startY、width和height属性初始化; { this.startX=startX; this.startY=startY; this.width=width; this.height=height; } PlainRect() //不带参数的构造方法,将矩形初始化为左上角坐标、长和宽都为0的矩形; { startX=0; startY=0; width=0; height=0; } boolean isInside(double x,double y) //判断某个点是否在矩形内部的方法isInside(double x,double y)。如在矩形内,返回true, 否则,返回false。 { if(x>=startX&&x<=(startX+width)&&y<startY&&y>=(startY-height)) {System.out.println("点在矩形内"); return true;} else {System.out.println("点不在矩形内"); return false;} }
package zhongqiuzuoye; //上课修改后的方法
public class PlainRect extends Rect{ private double startX; private double startY; public double getStartX() { return startX; } public void setStartX(double startX) { this.startX = startX; } public double getStartY() { return startY; } public void setStartY(double startY) { this.startY = startY; } PlainRect(double startX,double startY,double width,double height) //带4个参数的构造方法,用于对startX、startY、width和height属性初始化; { super(); this.startX=startX; this.startY=startY; } PlainRect() //不带参数的构造方法,将矩形初始化为左上角坐标、长和宽都为0的矩形; { this(0,0,0,0); } /*** * 判断点是否在矩形内 * @param x 点的X坐标 * @param y 点的Y坐标 * @return */ boolean isInside(double x,double y) //判断某个点是否在矩形内部的方法isInside(double x,double y)。如在矩形内,返回true, 否则,返回false。 { if(x>=startX&&x<=(startX+getWidth())&&y<startY&&y>=(startY-getHeight())) {System.out.println("点在矩形内"); return true;} else {System.out.println("点不在矩形内"); return false;} } }
package zhongqiuzuoye; public class TestPlainRect { public static void main(String[] args) { PlainRect p1=new PlainRect(10,10,20,10); p1.isInside(25.5, 13); p1.area(); p1.perimeter(); } }