BAEL-1848 final and immutable objects in Java (#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
This commit is contained in:
parent
d757050209
commit
6d56fc5438
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
public final class Currency {
|
||||
|
||||
private final String value;
|
||||
|
||||
private Currency(String currencyValue) {
|
||||
value = currencyValue;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Currency of(String value) {
|
||||
return new Currency(value);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
// 4. Immutability in Java
|
||||
public final class Money {
|
||||
private final double amount;
|
||||
private final Currency currency;
|
||||
|
||||
public Money(double amount, Currency currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public Currency getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public double getAmount() {
|
||||
return amount;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.immutableobjects;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ImmutableObjectsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCallingStringReplace_thenStringDoesNotMutate() {
|
||||
// 2. What's an Immutable Object?
|
||||
final String name = "baeldung";
|
||||
final String newName = name.replace("dung", "----");
|
||||
|
||||
assertEquals("baeldung", name);
|
||||
assertEquals("bael----", newName);
|
||||
}
|
||||
|
||||
public void whenReassignFinalValue_thenCompilerError() {
|
||||
// 3. The final Keyword in Java (1)
|
||||
final String name = "baeldung";
|
||||
// name = "bael...";
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddingElementToList_thenSizeChange() {
|
||||
// 3. The final Keyword in Java (2)
|
||||
final List<String> strings = new ArrayList<>();
|
||||
assertEquals(0, strings.size());
|
||||
strings.add("baeldung");
|
||||
assertEquals(1, strings.size());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue