java几何形状动态继承

时间:2017.10

作者:夏晓林

题目描述:


源代码:

package 多态;

class Shape1 {
	double getArea() {
		return 0;
	}

	double getCircumference() {
		return 0;
	}
}

class Circle extends Shape1 {
	double r;

	Circle(double r) {
		this.r = r;
	}

	public double getArea() {
		return (3.14 * r * r);
	}

	public double getCircumference() {
		return (2 * 3.14 * r);
	}
}

class Rectangle extends Shape1 {
	double a, b;

	Rectangle(double a, double b) {
		this.a = a;
		this.b = b;
	}

	public double getArea() {
		return (a * b);
	}

	public double getCircumference() {
		return (2 * a + 2 * b);
	}
}

class triangle extends Shape1 {
	double a, b, c, s, area;

	triangle(double a, double b, double c) {
		this.a = a;
		this.b = b;
		this.c = c;
	}

	public double getArea() {
		s = (a + b + c) / 2;
		area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
		return area;
	}

	public double getCircumference() {
		return (a + b + c);
	}
}

package 多态;

import javax.swing.JOptionPane;

public class Text {

	public static void main(String[] args) {
		int a1, b1, c1;
		String msg;
		msg = "请选择几何图形(1-矩形2-三角形3-圆形)";
		String Type = JOptionPane.showInputDialog(msg);
		Shape1 s = null;
		if ("1".equals(Type)) {
			msg = "请输入矩形的长:";
			String a = JOptionPane.showInputDialog(msg);
			a1 = Integer.parseInt(a);//将string转换为int型
			msg = "请输入矩形的宽:";
			String b = JOptionPane.showInputDialog(msg);
			b1 = Integer.parseInt(b);
			s = new Rectangle(a1, b1);
		} else if ("2".equals(Type)) {
			msg = "请输入第一条边的长度:";
			String a = JOptionPane.showInputDialog(msg);
			a1 = Integer.parseInt(a);
			msg = "请输入第二条边的长度:";
			String b = JOptionPane.showInputDialog(msg);
			b1 = Integer.parseInt(b);
			msg = "请输入第三条边的长度:";
			String c = JOptionPane.showInputDialog(msg);
			c1 = Integer.parseInt(c);
			s = new triangle(a1, b1, c1);
		} else if ("3".equals(Type)) {
			msg = "请输入半径的长度:";
			String a = JOptionPane.showInputDialog(msg);
			a1 = Integer.parseInt(a);
			s = new Circle(a1);
		}
		System.out.println("图形面积:" + s.getArea());
		System.out.println("图形周长:" + s.getCircumference());
	}
}
结果展示:


心得体会:

        通过这道题目更好的理解了动态多态的意义,基类的引用在调用方法可以根据实际对象的类型进行动态的选择,同时也学会了JOptionPane.showInputDialog的用法,它可以返回用户输入的字符串,JOptionpane类可以显示包含文本和按钮等的消息框,Integer.parseInt()可以把string型转换为int型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值