標籤:java
/**4-3
* 為實驗3中定義的矩形類派生一個子類:正方形類。若正方形的操作同樣是求周長和面積
* 則這個子類除了從父類那裡繼承來的方法之外,還需要定義哪些方法?
* 列出正方形類的所有域和方法。
* 編程檢查、運行所編寫的正方形類
**/
public class FirstProgram{public static void main (String[] args){Square square1 = new Square(8);Square square2 = new Square(25);System.out.println("The perimeter of square1 is: " + square1.perimeter());System.out.println("The area of square1 is: " + square1.area());System.out.println("The perimeter of square2 is: " + square2.perimeter());System.out.println("The area of square2 is: " + square2.area());}}class Rectangle{protected int length;protected int width;Rectangle (){}Rectangle(int l, int w){this.length = l;this.width = w;}int perimeter (){return (length + width) * 2;}int area (){return length * width;}} class Square extends Rectangle{protected int side;Square (int side){super();this.side = side;}int perimeter (){return 4 * side;}int area (){return side * side;}}
那些年,一起學的Java 4-3