[JAVA-621] core-java-lang-oop-constructors module

* Creation

* Moved code from https://www.baeldung.com/java-constructors

* Moved code from https://www.baeldung.com/java-copy-constructor

* Moved code from https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error

* Moved article references to the new README.md
This commit is contained in:
dupirefr
2020-04-02 21:04:24 +02:00
parent 825a362858
commit 29a0cc015f
16 changed files with 52 additions and 16 deletions

View File

@@ -4,15 +4,12 @@ This module contains articles about Object-oriented programming (OOP) in Java
### Relevant Articles:
- [Generic Constructors in Java](https://www.baeldung.com/java-generic-constructors)
- [Cannot Reference “X” Before Supertype Constructor Has Been Called](https://www.baeldung.com/java-cannot-reference-x-before-supertype-constructor-error)
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
- [Raw Types in Java](https://www.baeldung.com/raw-types-java)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Immutable Objects in Java](https://www.baeldung.com/java-immutable-object)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](https://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Static and Default Methods in Interfaces in Java](https://www.baeldung.com/java-static-default-methods)
- [Java Copy Constructor](https://www.baeldung.com/java-copy-constructor)
- [Abstract Classes in Java](https://www.baeldung.com/java-abstract-class)
- [[<-- Prev]](/core-java-modules/core-java-lang-oop)[[More -->]](/core-java-modules/core-java-lang-oop-3)

View File

@@ -1,68 +0,0 @@
package com.baeldung.constructors;
import java.time.LocalDateTime;
class BankAccount {
String name;
LocalDateTime opened;
double balance;
@Override
public String toString() {
return String.format("%s, %s, %f", this.name, this.opened.toString(), this.balance);
}
public String getName() {
return name;
}
public LocalDateTime getOpened() {
return opened;
}
public double getBalance() {
return this.balance;
}
}
class BankAccountEmptyConstructor extends BankAccount {
public BankAccountEmptyConstructor() {
this.name = "";
this.opened = LocalDateTime.now();
this.balance = 0.0d;
}
}
class BankAccountParameterizedConstructor extends BankAccount {
public BankAccountParameterizedConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
}
class BankAccountCopyConstructor extends BankAccount {
public BankAccountCopyConstructor(String name, LocalDateTime opened, double balance) {
this.name = name;
this.opened = opened;
this.balance = balance;
}
public BankAccountCopyConstructor(BankAccount other) {
this.name = other.name;
this.opened = LocalDateTime.now();
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,25 +0,0 @@
package com.baeldung.constructors;
import java.time.LocalDateTime;
class Transaction {
final BankAccountEmptyConstructor bankAccount;
final LocalDateTime date;
final double amount;
public Transaction(BankAccountEmptyConstructor account, LocalDateTime date, double amount) {
this.bankAccount = account;
this.date = date;
this.amount = amount;
}
/*
* Compilation Error :'(, all final variables must be explicitly initialised.
* public Transaction() {
* }
*/
public void invalidMethod() {
// this.amount = 102.03; // Results in a compiler error. You cannot change the value of a final variable.
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.copyconstructor;
import java.util.Date;
public class Employee {
protected int id;
protected String name;
protected Date startDate;
public Employee(int id, String name, Date startDate) {
this.id = id;
this.name = name;
this.startDate = startDate;
}
public Employee(Employee employee) {
this.id = employee.id;
this.name = employee.name;
this.startDate = new Date(employee.startDate.getTime());
}
Date getStartDate() {
return startDate;
}
public Employee copy() {
return new Employee(this);
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.copyconstructor;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public class Manager extends Employee {
private List<Employee> directReports;
public Manager(int id, String name, Date startDate, List<Employee> directReports) {
super(id, name, startDate);
this.directReports = directReports;
}
public Manager(Manager manager) {
super(manager.id, manager.name, manager.startDate);
this.directReports = manager.directReports.stream()
.collect(Collectors.toList());
}
@Override
public Employee copy() {
return new Manager(this);
}
List<Employee> getDirectReport() {
return this.directReports;
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.supertypecompilerexception;
public class MyClass {
private int myField1 = 10;
private int myField2;
public MyClass() {
//uncomment this to see the supertype compiler error:
//this(myField1);
}
public MyClass(int i) {
myField2 = i;
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.supertypecompilerexception;
public class MyClassSolution1 {
private int myField1 = 10;
private int myField2;
public MyClassSolution1() {
myField2 = myField1;
}
public MyClassSolution1(int i) {
myField2 = i;
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.supertypecompilerexception;
public class MyClassSolution2 {
private int myField1 = 10;
private int myField2;
public MyClassSolution2() {
setupMyFields(myField1);
}
public MyClassSolution2(int i) {
setupMyFields(i);
}
private void setupMyFields(int i) {
myField2 = i;
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.supertypecompilerexception;
public class MyClassSolution3 {
private static final int SOME_CONSTANT = 10;
private int myField2;
public MyClassSolution3() {
this(SOME_CONSTANT);
}
public MyClassSolution3(int i) {
myField2 = i;
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.supertypecompilerexception;
public class MyException extends RuntimeException {
private int errorCode = 0;
public MyException(String message) {
//uncomment this to see the supertype compiler error:
//super(message + getErrorCode());
}
public int getErrorCode() {
return errorCode;
}
}

View File

@@ -1,61 +0,0 @@
package com.baeldung.constructors;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.logging.Logger;
import static org.assertj.core.api.Assertions.*;
public class ConstructorUnitTest {
final static Logger LOGGER = Logger.getLogger(ConstructorUnitTest.class.getName());
@Test
public void givenNoExplicitContructor_whenUsed_thenFails() {
BankAccount account = new BankAccount();
assertThatThrownBy(() -> {
account.toString();
}).isInstanceOf(Exception.class);
}
@Test
public void givenNoArgumentConstructor_whenUsed_thenSucceeds() {
BankAccountEmptyConstructor account = new BankAccountEmptyConstructor();
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenParameterisedConstructor_whenUsed_thenSucceeds() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountParameterizedConstructor account =
new BankAccountParameterizedConstructor("Tom", opened, 1000.0f);
assertThatCode(() -> {
account.toString();
}).doesNotThrowAnyException();
}
@Test
public void givenCopyContructor_whenUser_thenMaintainsLogic() {
LocalDateTime opened = LocalDateTime.of(2018, Month.JUNE, 29, 06, 30, 00);
BankAccountCopyConstructor account = new BankAccountCopyConstructor("Tim", opened, 1000.0f);
BankAccountCopyConstructor newAccount = new BankAccountCopyConstructor(account);
assertThat(account.getName()).isEqualTo(newAccount.getName());
assertThat(account.getOpened()).isNotEqualTo(newAccount.getOpened());
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());
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.copyconstructor;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import java.util.Date;
import org.junit.Test;
public class EmployeeUnitTest {
@Test
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
Date d1 = new Date(123);
Employee e1 = new Employee(1, "Baeldung", d1);
Employee e2 = new Employee(e1);
assertEquals(d1, e1.getStartDate());
assertEquals(d1, e2.getStartDate());
d1.setTime(456);
assertEquals(d1, e1.getStartDate());
assertNotEquals(d1, e2.getStartDate());
}
@Test
public void givenCopyMethod_whenCopy_thenDistinct() {
Date d1 = new Date(123);
Employee e1 = new Employee(1, "Baeldung", d1);
Employee e2 = e1.copy();
assertEquals(d1, e1.getStartDate());
assertEquals(d1, e2.getStartDate());
d1.setTime(456);
assertEquals(d1, e1.getStartDate());
assertNotEquals(d1, e2.getStartDate());
}
}

View File

@@ -1,67 +0,0 @@
package com.baeldung.copyconstructor;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
public class ManagerUnitTest {
@Test
public void givenCopyConstructor_whenDeepCopy_thenDistinct() {
Date startDate = new Date(123);
Employee e1 = new Employee(1, "Baeldung", startDate);
Employee e2 = new Employee(e1);
List<Employee> directReports = new ArrayList<Employee>();
directReports.add(e1);
directReports.add(e2);
Manager m1 = new Manager(1, "Baeldung Manager", startDate, directReports);
Manager m2 = new Manager(m1);
List<Employee> directReports1 = m1.getDirectReport();
List<Employee> directReports2 = m2.getDirectReport();
assertEquals(directReports1.size(), directReports2.size());
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
// clear m1's direct reports list. m2's list should not be affected
directReports.clear();
directReports1 = m1.getDirectReport();
directReports2 = m2.getDirectReport();
assertEquals(0, directReports1.size());
assertEquals(2, directReports2.size());
}
@Test
public void givenCopyMethod_whenCopy_thenDistinct() {
Date startDate = new Date(123);
Employee e1 = new Employee(1, "Baeldung", startDate);
Employee e2 = new Employee(e1);
List<Employee> directReports = new ArrayList<Employee>();
directReports.add(e1);
directReports.add(e2);
// a Manager object whose declaration type is Employee.
Employee source = new Manager(1, "Baeldung Manager", startDate, directReports);
Employee clone = source.copy();
// after copy, clone should be still a Manager object.
assertTrue(clone instanceof Manager);
List<Employee> directReports1 = ((Manager) source).getDirectReport();
List<Employee> directReports2 = ((Manager) clone).getDirectReport();
assertEquals(directReports1.size(), directReports2.size());
assertArrayEquals(directReports1.toArray(), directReports2.toArray());
// clear source's direct reports list. clone's list should not be affected
directReports.clear();
directReports1 = ((Manager) source).getDirectReport();
directReports2 = ((Manager) clone).getDirectReport();
assertEquals(0, directReports1.size());
assertEquals(2, directReports2.size());
}
}