对于每个几何图形而言,都有一些共同的属性,如名字、面积等,而其计算面积的方法却各不相同。为了简化开发,请编写程序,定义一个超类来实现输入名字的方法,并使用抽象方法来计算面积。
思路分析:
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 |
public abstract class Shape { public
String getName() { //获得图形的名称 return
this .getClass().getSimpleName(); } public
abstract double getArea(); //获得图形的面积 } public class Circle extends
Shape { private
double radius; public
Circle( double
radius) { //获得圆形的半径 this .radius = radius; } @Override public
double getArea() { //计算圆形的面积 return
Math.PI * Math.pow(radius, 2 ); } } public
class Rectangle extends
Shape { private
double length; private
double width; public
Rectangle( double
length, double
width) { //获得矩形的长和宽 this .length = length; this .width = width; } @Override public
double getArea() { //计算矩形的面积 return
length * width; } } public
class Test { public
static void main(String[] args) { Circle circle = new
Circle( 1 ); //创建圆形对象并将半径设置成1 System.out.println( "图形的名称是:"
+ circle.getName()); System.out.println( "图形的面积是:"
+ circle.getArea()); Rectangle rectangle = new
Rectangle( 1 , 1 ); //创建矩形对象并将长和宽设置成1 System.out.println( "图形的名称是:"
+ rectangle.getName()); System.out.println( "图形的面积是:"
+ rectangle.getArea()); } } |
效果如图:
原文:http://www.cnblogs.com/cysolo/p/3560872.html