標籤:java
/**5-1
* 定義介面Printable,其中包括一個方法printItMyWay(),
* 這個方法沒有形參,傳回值為空白
**/
interface Printable{void printItMyWay();}
/**5-2
* 改寫實驗3中的矩形類,使之實現Printable介面,
* 用printItMyWay()方法將矩形的相關資訊(長、寬、周長、面積)
* 列印在螢幕上;
* 改寫實驗4中的正方形類,重載printItMyWay()方法
* 將正方形的相關資訊(邊長、周長、面積)列印在螢幕上
**/
public class FirstProgram{public static void main (String[] args){Rectangle rectangle = new Rectangle(12, 21);Square square = new Square(4);rectangle.printItMyWay();square.printItMyWay();}}interface Printable{void printItMyWay();} class Rectangle implements Printable{protected int length;protected int width;Rectangle (){}Rectangle(int l, int w){this.length = l;this.width = w;}void show(){System.out.println(" length: " + length + " width: " + width);}int perimeter (){return (length + width) * 2;}int area (){return length * width;} public void printItMyWay(){this.show();System.out.println(" permiter: " + this.perimeter() + " area: " + this.area());}} class Square extends Rectangle{protected int side;Square (int side){super();this.side = side;}void show(){System.out.println(" side: " + side);}int perimeter (){return 4 * side;}int area (){return side * side;}}
那些年,一起學的Java 5-1 5-2