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