结构推理 设计一个长方形类,成员变量包括长和宽。类中有计算面积和周长的方法,并有相应的set方法和get方法设置和获得长和宽。编写测试类测试是否达到预定功能。要求使用自定义的包。
【正确答案】package mypackage.math; class Rectangle{ private int length; private int width; public Rectangle(int length,int width){ this.length=length; this.width=width; } public void set(int length,int width){ this.length=length; this.width=width; } public void get(){ System.out.println("此长方形的长为"+length+"宽为"+width); } public int getLength(){ return length; } public int getWidth(){ return width; } public int calculatePerimeter(){ return 2*(length+width); } public int calculateArea(){ return (length*width); } public void print(){ System.out.println("此长方形的周长为"+calculatePerimeter()+"面积为"+calculateArea()); } } class Test{ public static void main(String [ ] args){ Rectangle myrectangle=new Rectangle(15,10); myrectangle.get(); myrectangle.print(); myrectangle.set(20,15); System.out.println("长方形的长是"+myrectangle.getLength()+"宽是"+ myrectangle .getWidth()); myrectangle.print(); } }
【答案解析】