/*
1, 定义一个函数,可以接收任何类型的图像,并且打印图形的面积和周长
2. 定义一个函数,可以返回任意类型的图像;
*/
//抽象类型-图像
abstract class Shade
{
String name;
public Shade(String name)
{
this.name = name;
}
abstract public void getArea();
abstract public void getLength();
}
//定义类 -- 圆形
class Circle extends Shade
{
public static final double PI = 3.14;
double r; //半径
public Circle(String name, double r)
{
super(name);
this.r = r;
}
public void getArea()
{
System.out.println(name + "的面积是: " + PI*r*r);
}
public void getLength()
{
System.out.println(name + "的周长是: " + 2*PI*r);
}
}
//定义类 -- 长方形
class Retangle extends Shade
{
double length;
double width;
public Retangle(String name, double length, double width)
{
super(name);
this.length = length;
this.width = width;
}
public void getArea()
{
System.out.println(name + "的面积是: " + length*width);
}
public void getLength()
{
System.out.println(name + "的周长是: " + 2*(length+width));
}
}
class Demo11
{
public static void main(String[] args)
{
//定义一个圆形
Shade c1 = new Circle("圆形1", 12.1);
printAreaAndLength(c1);
//定义一个长方形
Shade r1 = new Retangle("长方形1", 13, 13);
printAreaAndLength(r1);
//创建一个圆形
Shade c2 = getShade(0);
printAreaAndLength(c2);
//创建一个长方形
Shade r2 = getShade(2);
printAreaAndLength(r2);
}
//接收任意类型的对象
public static void printAreaAndLength(Shade shade)
{
shade.getArea();
shade.getLength();
}
//返回任意类型的变量
public static Shade getShade(int i)
{
if (i == 0)
{
return new Circle("圆形2",2.1);
}
else
{
return new Retangle("长方形2", 10, 22.1);
}
}
}