forked from DH-Cologne/java-wegweiser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Final.md
84 lines (52 loc) · 2.3 KB
/
Final.md
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
# `final`
> :construction: **TODO:**
> - gründlichere Formulierungen in ganzen Sätzen
- [`final`](#final)
- [Finale Variablen](#finale-variablen)
- [Finale Methoden](#finale-methoden)
- [Finale Klassen](#finale-klassen)
- [Konstanten in Java](#konstanten-in-java)
Das Schlüsselwort `final` markiert eine (benannte) Einheit (Variable, Methode oder Klasse), der nur ein einziges mal ein Wert (o.ä.) zugewiesen werden kann. Dies hat in unterschiedlichen Kontexten unterschiedliche Bedeutungen ...
## Finale Variablen
> :construction: **TODO**
- primitive: Wert kann nicht geändert werden
- komplexe: Referenz kann nicht auf anderes Objekt geändert werden, aber Felder des Objektes können geändert werden
- Unterschied zu z.B. C++ `const`: finale Variablen können auch noch _nach_ der Deklaration einen Wert erhalten, aber eben nur ein mal!
Im folgenden Beispiel kann der Name des Users nur einmal (bei Instanziierung der Klasse bzw. Erzeugung eines Objektes) gesetzt werden. Der Wert kann dann für dieses Objekt nicht mehr geändert werden. Die Instanziierung (Aufruf des Konstruktors) ist _der letzte mögliche Zeitpunkt zum Setzen eines Wertes für dieses finale Klassenattribut!_
```java
public class User {
private final String name;
public User(String name){
this.name = name;
}
}
```
## Finale Methoden
> :construction: **TODO**
Finale Methoden können nicht überschrieben werden.
```java
public final void someMethod(){
// Diese Methode kann in einer erweiternden Klasse nicht überschrieben werden!
}
```
## Finale Klassen
> :construction: **TODO**
Finale Klassen können nicht erweitert werden.
```java
final class ImmutableClass {
// Diese Klasse kann nicht erweitert werden!
}
```
## Konstanten in Java
> :construction: **TODO**
Konstanten (hier: unveränderbare Felder, die _immer_ den selben Wert haben) werden mit `static` _und_ `final` deklariert und befolgen die Naming Conventions:
```java
// könnte auch "public" sein
private static final int THIS_IS_A_PRIVATE_CONSTANT = 2;
```
<!-- Dieses HTML-Snippet sollte am Ende jeder Seite stehen! -->
<div class="top-link">
<a href="#" title="Zum Anfang scrollen!">Top :balloon:</a>
<br/>
<a href="https://dh-cologne.github.io/java-wegweiser#inhalt-book" title="Zurück zur Übersicht!">Inhalt :book:</a>
</div>