首页 > 其他 > 详细

关于抽象类的一个实例

时间:2014-04-12 08:33:57      阅读:748      评论:0      收藏:0      [点我收藏+]




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();
	}

}


测试结果:

bubuko.com,布布扣








关于抽象类的一个实例,布布扣,bubuko.com

关于抽象类的一个实例

原文:http://blog.csdn.net/aidpcx/article/details/23470447

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!