简单的java 编程题 关于继承

一、编写一个矩形类Rect,该类包含:1、2个私有属性。矩形的长length和宽width。2、1个构造方法。带2个参数的构造方法,用于对length和width属性进行初始化。3、length和width属性的set和get方法。4、2个公有成员方法。分别用于计算并返回矩形的面积和周长。二、编写一个具有确定位置的矩形类PlainRect,该类继承于Rect类,其确定位置用矩形的左上角坐标来标识,为该类添加:1、2个属性。矩形左上角坐标startX和startY。2、2个构造方法。(1)带4个参数的构造方法。用于对startX、startY、length和width属性进行初始化。(2)不带参数的构造方法。将矩形初始化为左上角坐标、长、宽都为0的矩形。3、1个方法。方法isInside(double x,double y),用于判断某个点是否在矩形内部,如在矩形内,返回true,否则,返回false。三、编写上题PlainRect类的测试程序:1、创建一个左上角坐标为(10,10),长为20,宽为10的矩形对象。2、计算并打印出矩形的面积和周长。3、判断点(25.5,13)是否在矩形内,并打印输出相关信息。

package javaapplication4;
public class Rect {
protected int length;/////这个地方不能变成私有属性,因为后面继承的类也需要继承它。
protected int width;
public Rect(int length,int width)
{
this.length=length;
this.width=width;
}
public void setLength(int length)
{this.length=length;<br> }
public void setWidth(int width)
{this.width=width;<br> }
public int getLength()
{return length;<br> }
public int getWidth()
{return width;<br> }
public int getArea()
{return length*width;<br> }
public int getCycle()
{return (length+width)*2;<br> }}
////////////////////////////////////////////////////////////////////////////////////////////////////////
package javaapplication4;
public class PlainRect extends Rect
{///此类并未继承父类的长宽属性,所以父类的设计是不合理的。应将其属性改为protected.
protected int startX,startY;
public PlainRect(int length,int width,int startx,int starty)
{
super(length,width);
startX=startx;
startY=starty;
}
public PlainRect()
{
super(0,0);
startX=0;
startY=0;
}
public boolean isInside(double x,double y)
{
boolean b=false;
if(x>startX&&x<startX+length)
if(y>startY&&y<startY+width)
b=true;
return b; }}
////////////////////////////////////////////////////////////////////////////////////////////////////////
package javaapplication4;
public class Main {
public static void main(String[] args) {
PlainRect Pr1=new PlainRect(20,10,10,10);
System.out.println("面积为:"+Pr1.getArea());
System.out.println("周长为:"+Pr1.getCycle());
System.out.println("点(25.5,13)"+(Pr1.isInside(25.5, 13)?"在":"不在")+"此方形内");
} }
温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答