//该代码实现结果为如果设定的长和宽相等则实例化正方形(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:高等教育出版社的书,“不'错'~~~~(>_