新浪博客

分别用面向对象和面向过程编程方法计算长方形的周长和面积。

2006-09-22 09:47阅读:
//用面向对象的方法来设计计算长方形的周长和面积。
/*思考如下:
1。一个长方形可以看成一个长方形对象。
2。一个长方形对象有两个状态(长和宽)和两个行为(求周长和求面积)。
3。将所有长方形的共性抽取出来,设计一个长方形类。
4。通过长方形对象的行为,就可以求出某个具体的长方形对象的周长和面积。
*/
class Rectangle
{
int l,w;
//构造计算长方形周长的方法
int perimeter()
{
return 2*(l+w);
}
//构造计算长方形面积的方法
int area()
{
return l*w;
}
public static void main(String[] args)
{
Rectangle rect1=new Rectangle();//实例化一个对象rect1
Rectangle rect2=new Rectangle();//实例化一个对象rect2

rect1.l=10;//为对象赋初值
rect1.w=5;//为对象赋初值
System.out.println('perimeter of rect1 ='+rect1.perimeter());
System.out.println('area of rect1 ='+rect1.area());

rect2.l=6;//为对象赋初值
rect2.w=10;//为对象赋初值
System.out.println('perimeter of rect2 ='+rect2.perimeter());
System.out.println('area of rect2 ='+rect2.area());
}
}

//用面积过程的程序设计方式思考:
/*
1。确定长方形的周长和面积的算法。
2。编写两个方法(函数)分别计算长方形的周长和面积。
3。求财长的方法(函数)和求面积的方法(函数)需要两个参数,分别是长方形的长和宽。
*/
/*
class Rectangle
{
static int perimeter(int length,int width)
{
return 2*(length+width);
}
static int area(int length,int width)
{
return length*width;
}
public static void main(Sting[] args)
{
System.out.println('perimeter='+Rectangle.perimeter(5,4));
System.out.println('area='+Rectangle.area(5,4));
}
}
*/

我的更多文章

下载客户端阅读体验更佳

APP专享