您的位置:首页 > 编程语言 > Java开发

纯作业代码——Java实现接口、继承

2009-10-16 19:33 716 查看
//该代码实现结果为如果设定的长和宽相等则实例化正方形(Square)的类,否则实例化矩形类。
interface rect{
	public double area();
	public void getWidth(double Width);
	public void getHeight(double Height);
}
class Rectangle1 implements rect{
	double _width,_height;
	public void getWidth(double Width){
		_width=Width;
	}
	public void getHeight(double Height){
		_height=Height;
	}
	public double area(){
		return(_width*_height);
	}
}
class Square extends Rectangle1{
	public double area(){
		return(_width*_width);
	}
}
public class test1{
//At here ,I use the super class to define rect1.
	static Rectangle1 rect1;   
//set the value of width and height,then judge the shape,and  Print them
	public static void SetValue(double width ,double height){  
		if(width==height) rect1=new Square();     
	    else rect1=new Rectangle1();
		
		rect1.getWidth(width);
		System.out.println("The Width value is :"+width+".");
		rect1.getHeight(height);
		System.out.println("The Height value is :"+height+".");
		
		if(width==height) System.out.println("The shape is Square!");
		else System.out.println("The shape is Rectangle!");
	}
//get the result,and print it
	public static void CalcIt(){
		System.out.println("The result is :"+rect1.area()+".");
	}
	public static void main(String args[]){
		//set the width and height
		SetValue(10,10);
		CalcIt();
		System.out.println('/n');
		//set the width and height
		SetValue(10,50); 
		CalcIt();
	}
}




这是教材上的一道题。首先写了一个计算矩形的类,然后再让写一个正方形的类来继承矩形类。并且要求重写父类中的至少一个方法。

于是有了这段代码。



各位尽管点评。







ps:高等教育出版社的书,“不'错'~~~~(>_<)~~~~ ”
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐