/**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; } }
时间: 2024-10-15 13:41:48