-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractClassExample.java
More file actions
101 lines (83 loc) · 1.97 KB
/
AbstractClassExample.java
File metadata and controls
101 lines (83 loc) · 1.97 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
97
98
99
100
101
package class_ex;
/**
* abstract class 範例
*
* Reference
* - https://matthung0807.blogspot.com/2020/04/java-abstract-class-interface-difference.html
*/
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(2, 5);
Circle circle = new Circle(3);
//! abstract class不能被實體化
// Shape shape = new Shape();
System.out.println("Area of rectangle: " + rectangle.area());
System.out.println("Area of circle: " + circle.area());
rectangle.draw();
circle.draw();
rectangle.printClassName();
circle.printClassName();
}
}
/**
* interface Figure
*/
interface Figure {
public abstract void draw();
public abstract double area();
public void printClassName();
}
/**
* Abstract class
*/
abstract class Shape implements Figure {
// public double area() {
// return 0;
// };
// abstract method 抽象方法
@Override
public void printClassName() {
System.out.println("Shape class.");
}
}
/**
* Rectangle 繼承 Shape,即為形成 IS-A
*/
class Rectangle extends Shape {
protected double height;
protected double width;
Rectangle(double h, double w) {
this.height = h;
this.width = w;
}
@Override
public double area() {
return height * width;
}
@Override
public void draw() {
System.out.println("The rectangle is drawing.");
}
@Override
public void printClassName() {
System.out.println("Rectangle class");
}
}
class Circle extends Shape {
protected double r;
Circle(double r) {
this.r = r;
}
@Override
public double area() {
return Math.PI * r * r;
}
@Override
public void draw() {
System.out.println("The circle is drawing.");
}
@Override
public void printClassName() {
System.out.println("Circle class.");
}
}