// The <SPAN class = 'wp _ keywordlink '> Code </span> is implemented to instantiate the square class if the length and width are equal, otherwise, the rectangle class is instantiated. <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/> class square extends rectangle1 {<br/> Public double area () {<br/> return (_ width * _ width ); <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/>
This is a question in the teaching material. First, I wrote a class to calculate the rectangle, and then I wrote a square class to inherit the rectangle class. In addition, at least one method in the parent class must be rewritten.
So we have this code.
Comments.
PS: The Book of the Higher Education Publishing House, "No 'error '~~~~ (>_< )~~~~ "