标签: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
原文地址:http://anglecode.blog.51cto.com/5628271/1619856