add constructor chaining example (#7125)

This commit is contained in:
Carlos Cano 2019-07-21 05:20:19 +02:00 committed by Josh Cummings
parent 8e6a12f1a2
commit 7eaa85d524
2 changed files with 36 additions and 14 deletions

View File

@ -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);
}
}

View File

@ -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());
}
}