关于抽象类的一个实例




package abstract_shape;
/*
 * 
 * 编写一个抽象类Shape,声明计算图形面积的抽象方法。
 * 再分别定义Shape的子类Circle(圆)和Rectangle(矩形),
 * 在两个子类中按照不同图形的面积计算公式,实现Shape类中
 * 计算面积的方法。最后在测试类中申明一个Shape对象,创建
 * 一个圆对象,创建一个矩形对象,将圆对象和矩形对象分别赋
 * 予Shape对象,通过Shape对象计算圆的面积和矩形的面积(抽象类实现多态)
 */
abstract class shape {
	abstract double getArea();
}

class circle extends shape{
	double r;
	public circle(double rr){
		r = rr;
	}
	double getArea(){
		return Math.PI * r * r;
	}
}

class rectangle extends shape{
	double width;
	double length;
	public rectangle(double l,double w){
		length = l;
		width = w;
	}
	public double getArea(){
		return length * width;
	}
	
}


package abstract_shape;

public class Test_shape {

	public static void main(String[] args) {
		shape s;
		circle c = new circle(30);
		rectangle r = new rectangle(30,40);
		System.out.println("圆面积:    " + c.getArea());
		System.out.println("矩形面积:    " + r.getArea());
		System.out.println();
		
		s = c;
		System.out.println("对象上转型-圆面积:    ");
		System.out.println("圆面积:    " + s.getArea());
		System.out.println();
		
		s = r;
		System.out.println("对象上转型-矩形面积:    ");
		System.out.println("矩形面积:    " + s.getArea());
		System.out.println();
	}

}


测试结果:

关于抽象类的一个实例_第1张图片








你可能感兴趣的:(java学习)