forked from javakurssi/Tuntimateriaalit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShapeInterface.java
More file actions
96 lines (76 loc) · 2.7 KB
/
Copy pathShapeInterface.java
File metadata and controls
96 lines (76 loc) · 2.7 KB
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
package lesson4;
/**
* This example illustrates the usage of a simple Shape interface
*/
public class ShapeInterface {
public static void main(String[] args) {
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
// Note that we can't create an instance of an interface!
// Shape randomShape = new Shape();
System.out.println("Circle area: " + circle.calculateArea());
System.out.println("Rectangle area: " + rectangle.calculateArea());
System.out.println("Circle as string: " + circle);
System.out.println("Rectangle as string: " + rectangle);
// isLargerThan and totalPerimeter methods accept any kind of Shape interface object
System.out.println("Is circle larger?: " + isLargerThan(circle, rectangle));
System.out.println("Total perimeter: " + totalPerimeter(circle, rectangle));
}
// We don't need to know the exact class of the shape; it is enough that it implements the Shape interface
// => The method becomes much more reusable in the code
public static boolean isLargerThan(Shape a, Shape b) {
return a.calculateArea() > b.calculateArea();
}
public static double totalPerimeter(Shape a, Shape b) {
return a.calculatePerimeter() + b.calculatePerimeter();
}
}
// The Shape interface specifies common methods for all shapes (circle, rectangle, triangle, etc.)
interface Shape {
// Note that interfaces don't have attributes or a constructor!
// Class that implements this Shape interface needs to provide implementation for ALL of its methods!
double calculateArea();
double calculatePerimeter();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
@Override
public String toString() {
return "Radius: " + radius;
}
// Classes that implement an interface can have methods of their own
public double getDiameter() {
return 2 * radius;
}
}
class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
@Override
public double calculatePerimeter() {
return 2 * width + 2 * height;
}
@Override
public String toString() {
return "Width: " + width + " Height: " + height;
}
}