本文实例讲述了java用接口、多态、继承、类计算三角形和矩形周长及面积的方法。分享给大家供大家参考。具体如下:
定义接口规范:
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
/** * @author vvv * @date 2013-8-10 上午08:56:48 */ package com.duotai; /** * * */ public interface Shape { public double area(); public double longer(); } /** * @author vvv * @date 2013-8-10 上午09:10:06 */ package com.duotai; /** * * */ public class Triangle implements Shape { double s1; double s2; double s3; // 初始化一个三角形对象,并赋予该三角形三边长 public Triangle( double s1, double s2, double s3) { if (isTri(s1, s2, s3)) { this .s1 = s1; this .s2 = s2; this .s3 = s3; } else { System.out.println( "输入的三边长" + s1 + "、" + s2 + "、" + s3 + "不能组成一个三角形,请重新输入三边长!" ); } } // 判断是否是个三角形 public boolean isTri( double s1, double s2, double s3) { if (s1 + s2 < s3) { return false ; } if (s1 + s3 < s2) { return false ; } if (s2 + s3 < s1) { return false ; } return true ; } /* * (non-Javadoc) * * @see com.duotai.Shape#area() */ @Override public double area() { double p = (s1 + s2 + s3) / 2; return Math.sqrt(p * (p - s1) * (p - s2) * (p - s3)); } /* * (non-Javadoc) * * @see com.duotai.Shape#longer() */ @Override public double longer() { return s1 + s2 + s3; } } /** * @author vvv * @date 2013-8-10 上午09:12:06 */ package com.duotai; /** * * */ public class Director implements Shape { double s1; double s2; // 初始化一个长方形,并赋予该长方形两边长 public Director(double s1, double s2) { this.s1 = s1; this.s2 = s2; } /* * (non-Javadoc) * * @see com.duotai.Shape#area() */ @Override public double area() { // TODO Auto-generated method stub return s1 * s2; } /* * (non-Javadoc) * * @see com.duotai.Shape#longer() */ @Override public double longer() { // TODO Auto-generated method stub return 2 * (s1 + s2); } } /** * @author vvv * @date 2013-8-10 上午09:13:30 */ package com.duotai; /** * * */ public class Test { /** * @param args */ public static void main(String[] args) { Shape triangle = new Triangle( 3 , 4 , 8 ); // 新建一个三边长为3,4,5的三角形 Shape tri = new Triangle( 3 , 4 , 5 ); Shape director = new Director( 10 , 20 ); // 新建一个两边长为10,20的长方形 System.out.println( "三角形triangle的周长为:" + triangle.longer()); System.out.println( "三角形triangle的面积为:" + triangle.area()); System.out.println( "三角形tri的周长为:" + tri.longer()); System.out.println( "三角形tri的面积为:" + tri.area()); System.out.println( "该长方形的周长为:" + director.longer()); System.out.println( "该长方形的面积为:" + director.area()); } } |
希望本文所述对大家的java程序设计有所帮助。