1. 程式人生 > >java幾何形狀動態繼承

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型。