You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Abstract classes are classes which you cannot make an instance of directly.[^concrete]
4
+
5
+
```java,does_not_compile
6
+
abstract class Plant {}
7
+
8
+
void main() {
9
+
// You cannot make an instance because
10
+
// it is an abstract class.
11
+
var p = new Plant();
12
+
}
13
+
```
14
+
15
+
The use-case for these is making classes which are designed to be subclassed.
16
+
An example of this that comes with Java is `AbstractList`.
17
+
18
+
`AbstractList` defines most of the methods required by the `List` interface and is intended to
19
+
lower the effort required to make a custom `List` implementation.
20
+
21
+
```java
22
+
importjava.util.AbstractList;
23
+
24
+
// This subclass is a List containing the numbers 5 and 7
25
+
classFiveAndSeven
26
+
// Almost all of the implementation is inherited from AbstractList
27
+
extendsAbstractList<Integer> {
28
+
29
+
@Override
30
+
publicIntegerget(intindex) {
31
+
returnswitch (index) {
32
+
case0->5;
33
+
case1->7;
34
+
default->thrownewIndexOutOfBoundsException();
35
+
};
36
+
}
37
+
38
+
@Override
39
+
publicintsize() {
40
+
return2;
41
+
}
42
+
}
43
+
44
+
void main() {
45
+
var l =newFiveAndSeven();
46
+
IO.println(l);
47
+
}
48
+
```
49
+
50
+
[^concrete]: "Abstract" as a term here means something close to "not in reality." You will hear people refer to non-abstract classes as "concrete" classes.
0 commit comments