//該代碼實現結果為如果設定的長和寬相等則執行個體化正方形(Square)的類,否則執行個體化矩形類。<br />interface rect{<br />public double area();<br />public void getWidth(double Width);<br />public void getHeight(double Height);<br />}<br />class Rectangle1 implements rect{<br />double _width,_height;<br />public void getWidth(double Width){<br />_width=Width;<br />}<br />public void getHeight(double Height){<br />_height=Height;<br />}<br />public double area(){<br />return(_width*_height);<br />}<br />}<br />class Square extends Rectangle1{<br />public double area(){<br />return(_width*_width);<br />}<br />}<br />public class test1{<br />//At here ,I use the super class to define rect1.<br />static Rectangle1 rect1;<br />//set the value of width and height,then judge the shape,and Print them<br />public static void SetValue(double width ,double height){<br />if(width==height) rect1=new Square();<br /> else rect1=new Rectangle1();</p><p>rect1.getWidth(width);<br />System.out.println("The Width value is :"+width+".");<br />rect1.getHeight(height);<br />System.out.println("The Height value is :"+height+".");</p><p>if(width==height) System.out.println("The shape is Square!");<br />else System.out.println("The shape is Rectangle!");<br />}<br />//get the result,and print it<br />public static void CalcIt(){<br />System.out.println("The result is :"+rect1.area()+".");<br />}<br />public static void main(String args[]){<br />//set the width and height<br />SetValue(10,10);<br />CalcIt();<br />System.out.println('/n');<br />//set the width and height<br />SetValue(10,50);<br />CalcIt();<br />}<br />}<br />
這是教材上的一道題。首先寫了一個計算矩形的類,然後再讓寫一個正方形的類來繼承矩形類。並且要求重寫父類中的至少一個方法。
於是有了這段代碼。
各位儘管點評。
ps:高等教育出版社的書,“不'錯'~~~~(>_<)~~~~ ”