標籤:java
/**5-3
* 在Printable介面中增加一個新的PrintItMyWay(char)方法,
* 這個方法有一個字元型的形參,傳回值為空白.
* 其功能是利用給出的字元列印,例如如果給定字元為*,一個長為4
* 寬為3的矩形的螢幕列印結果為:
* ****
* ****
* ****
**/
public class FirstProgram{public static void main (String[] args){Rectangle rectangle = new Rectangle(5, 3);Square square = new Square(4);rectangle.printItMyWay(‘*‘);square.printItMyWay(‘*‘);}}interface Printable{void printItMyWay();void printItMyWay(char n);} 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);}void print(char n){int i, j;for (i = 0; i < width; i++){for (j = 0; j < length; j++)System.out.print(" " + n + " ");System.out.println();}System.out.println();}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());} public void printItMyWay(char n) { this.print(n); }} class Square extends Rectangle{protected int side;Square (int side){super();this.side = side;}void show(){System.out.println(" side: " + side);}void print(char n){int i, j;for (i = 0; i < side; i++){for (j = 0; j < side; j++)System.out.print(" " + n + " ");System.out.println();}}int perimeter (){return 4 * side;}int area (){return side * side;}}
本文出自 “hacker” 部落格,請務必保留此出處http://anglecode.blog.51cto.com/5628271/1619857
那些年,一起學的Java 5-3