add constructor chaining example (#7125)
This commit is contained in:
parent
8e6a12f1a2
commit
7eaa85d524
|
@ -54,3 +54,15 @@ class BankAccountCopyConstructor extends BankAccount {
|
|||
this.balance = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
class BankAccountChainedConstructors extends BankAccount {
|
||||
public BankAccountChainedConstructors(String name, LocalDateTime opened, double balance) {
|
||||
this.name = name;
|
||||
this.opened = opened;
|
||||
this.balance = balance;
|
||||
}
|
||||
|
||||
public BankAccountChainedConstructors(String name) {
|
||||
this(name, LocalDateTime.now(), 0.0f);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,14 @@
|
|||
package com.baeldung.constructors;
|
||||
|
||||
import com.baeldung.constructors.*;
|
||||
import com.google.common.collect.Comparators;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
import java.util.ArrayList;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
public class ConstructorUnitTest {
|
||||
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
|
||||
|
@ -17,7 +16,9 @@ public class ConstructorUnitTest {
|
|||
@Test
|
||||
public void givenNoExplicitContructor_whenUsed_thenFails() {
|
||||
BankAccount account = new BankAccount();
|
||||
assertThatThrownBy(() -> { account.toString(); }).isInstanceOf(Exception.class);
|
||||
assertThatThrownBy(() -> {
|
||||
account.toString();
|
||||
}).isInstanceOf(Exception.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -50,4 +51,13 @@ public class ConstructorUnitTest {
|
|||
|
||||
assertThat(newAccount.getBalance()).isEqualTo(0.0f);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenChainedConstructor_whenUsed_thenMaintainsLogic() {
|
||||
BankAccountChainedConstructors account = new BankAccountChainedConstructors("Tim");
|
||||
BankAccountChainedConstructors newAccount = new BankAccountChainedConstructors("Tim", LocalDateTime.now(), 0.0f);
|
||||
|
||||
assertThat(account.getName()).isEqualTo(newAccount.getName());
|
||||
assertThat(account.getBalance()).isEqualTo(newAccount.getBalance());
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue