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();
}
}
