Skip to content

Commit 6d56fc5

Browse files
pablonvzpedja4
authored andcommitted
BAEL-1848 final and immutable objects in Java (eugenp#4515)
* Strange git issue with README.MD, wouldn't revert the file * final and immutable objects in Java * Move tests to src/test/ * BAEL-1848 renamed test class
1 parent d757050 commit 6d56fc5

3 files changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.baeldung.immutableobjects;
2+
3+
public final class Currency {
4+
5+
private final String value;
6+
7+
private Currency(String currencyValue) {
8+
value = currencyValue;
9+
}
10+
11+
public String getValue() {
12+
return value;
13+
}
14+
15+
public static Currency of(String value) {
16+
return new Currency(value);
17+
}
18+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.baeldung.immutableobjects;
2+
3+
// 4. Immutability in Java
4+
public final class Money {
5+
private final double amount;
6+
private final Currency currency;
7+
8+
public Money(double amount, Currency currency) {
9+
this.amount = amount;
10+
this.currency = currency;
11+
}
12+
13+
public Currency getCurrency() {
14+
return currency;
15+
}
16+
17+
public double getAmount() {
18+
return amount;
19+
}
20+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.baeldung.immutableobjects;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
import org.junit.Test;
9+
10+
public class ImmutableObjectsUnitTest {
11+
12+
@Test
13+
public void whenCallingStringReplace_thenStringDoesNotMutate() {
14+
// 2. What's an Immutable Object?
15+
final String name = "baeldung";
16+
final String newName = name.replace("dung", "----");
17+
18+
assertEquals("baeldung", name);
19+
assertEquals("bael----", newName);
20+
}
21+
22+
public void whenReassignFinalValue_thenCompilerError() {
23+
// 3. The final Keyword in Java (1)
24+
final String name = "baeldung";
25+
// name = "bael...";
26+
}
27+
28+
@Test
29+
public void whenAddingElementToList_thenSizeChange() {
30+
// 3. The final Keyword in Java (2)
31+
final List<String> strings = new ArrayList<>();
32+
assertEquals(0, strings.size());
33+
strings.add("baeldung");
34+
assertEquals(1, strings.size());
35+
}
36+
}

0 commit comments

Comments
 (0)