純作業代碼——Java實現介面、繼承

來源:互聯網
上載者:User

//該代碼實現結果為如果設定的長和寬相等則執行個體化正方形(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:高等教育出版社的書,“不'錯'~~~~(>_<)~~~~ ”

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.