时间: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型。