JAVA小练习69——需求: 定义了图形、 矩形、 圆形三个类,所有的图形都具备计算面积与周长的方法, 只不过每种图形计算方式并不一致

要求:
1. 定义一个方法可以接受 任意类型的图形对象,在方法内部调用图形周长与面积的方法。
2. 定义一个方法可以返回任意类型的图形对象。

//图形类
abstract class MyShape{

	public abstract void getLength();

	public abstract void getArea();
}

//矩形
class Rect extends MyShape{

	int width;

	int height;

	public Rect(int width,int height){
		this.width = width;
		this.height =height;
	}

	public  void getLength(){
		System.out.println("矩形的周长:"+ 2*(width+height));
	}

	public  void getArea(){
		System.out.println("矩形的面积:"+ width*height);
	}
}

//圆形
class Circle extends MyShape{
	
	public static final double PI = 3.14;

	double r;

	public Circle(double r){
		this.r =r;
	}
	
	public  void getLength(){
		System.out.println("圆形的周长:"+ 2*PI*r);
	}

	public  void getArea(){
		System.out.println("圆形的面积:"+ PI*r*r);
	}

}




class Demo69
{
	public static void main(String[] args) 
	{
		
		MyShape m = getShape(1);
								
		print(m);
		
	}

	//定义一个方法可以接受 任意类型的图形对象,在方法内部调用图形周长与面积的方法
	public static void print(MyShape m){
		m.getArea();
		m.getLength();
	}


	//定义一个方法可以返回任意类型的图形对象。
	public static  MyShape  getShape(int i){
		if(0==i){
			return new Circle(4.0);
		}else{
			return new Rect(3,4);
		}

	}


}



猜你喜欢

转载自blog.csdn.net/Eric_The_Red/article/details/90519772