Split or move core-java-modules/core-java-lang-oop module (#7767)

This commit is contained in:
Catalin Burcea
2019-09-12 12:32:10 +03:00
committed by Josh Cummings
parent 71818a79cc
commit ec23ab367e
76 changed files with 124 additions and 71 deletions

View File

@@ -12,13 +12,4 @@
- [Object Type Casting in Java](http://www.baeldung.com/java-type-casting)
- [The “final” Keyword in Java](http://www.baeldung.com/java-final)
- [Type Erasure in Java Explained](http://www.baeldung.com/java-type-erasure)
- [Pass-By-Value as a Parameter Passing Mechanism in Java](http://www.baeldung.com/java-pass-by-value-or-pass-by-reference)
- [Variable and Method Hiding in Java](http://www.baeldung.com/java-variable-method-hiding)
- [Access Modifiers in Java](http://www.baeldung.com/java-access-modifiers)
- [Guide to the super Java Keyword](http://www.baeldung.com/java-super)
- [Guide to the this Java Keyword](http://www.baeldung.com/java-this)
- [Immutable Objects in Java](http://www.baeldung.com/java-immutable-object)
- [Inheritance and Composition (Is-a vs Has-a relationship) in Java](http://www.baeldung.com/java-inheritance-composition)
- [A Guide to Constructors in Java](https://www.baeldung.com/java-constructors)
- [Java equals() and hashCode() Contracts](https://www.baeldung.com/java-equals-hashcode-contracts)
- [Marker Interfaces in Java](https://www.baeldung.com/java-marker-interfaces)

View File

@@ -56,12 +56,6 @@
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
<version>${equalsverifier.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@@ -78,7 +72,6 @@
<gson.version>2.8.2</gson.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
<equalsverifier.version>3.0.3</equalsverifier.version>
</properties>
</project>

View File

@@ -1,9 +0,0 @@
package com.baeldung.accessmodifiers;
public class Public {
public Public() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in the same package or subclass.
SuperPublic.defaultMethod(); // Available in the same package.
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.accessmodifiers;
public class SubClass extends SuperPublic {
public SubClass() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in the same package or subclass.
SuperPublic.defaultMethod(); // Available in the same package.
}
}

View File

@@ -1,39 +0,0 @@
package com.baeldung.accessmodifiers;
//Only public or default access modifiers are permitted
public class SuperPublic {
// Always available from anywhere
static public void publicMethod() {
System.out.println(SuperPublic.class.getName() + " publicMethod()");
}
// Available within the same package
static void defaultMethod() {
System.out.println(SuperPublic.class.getName() + " defaultMethod()");
}
// Available within the same package and subclasses
static protected void protectedMethod() {
System.out.println(SuperPublic.class.getName() + " protectedMethod()");
}
// Available within the same class only
static private void privateMethod() {
System.out.println(SuperPublic.class.getName() + " privateMethod()");
}
// Method in the same class = has access to all members within the same class
private void anotherPrivateMethod() {
privateMethod();
defaultMethod();
protectedMethod();
publicMethod(); // Available in the same class only.
}
}
// Only public or default access modifiers are permitted
class SuperDefault {
public void publicMethod() {
System.out.println(this.getClass().getName() + " publicMethod()");
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherPublic {
public AnotherPublic() {
SuperPublic.publicMethod(); // Available everywhere.
}
}

View File

@@ -1,10 +0,0 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherSubClass extends SuperPublic {
public AnotherSubClass() {
SuperPublic.publicMethod(); // Available everywhere.
SuperPublic.protectedMethod(); // Available in subclass. Let's note different package.
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.accessmodifiers.another;
import com.baeldung.accessmodifiers.SuperPublic;
public class AnotherSuperPublic {
public AnotherSuperPublic() {
SuperPublic.publicMethod(); // Available everywhere. Let's note different package.
}
}

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,36 +0,0 @@
package com.baeldung.equalshashcode;
class Money {
int amount;
String currencyCode;
Money(int amount, String currencyCode) {
this.amount = amount;
this.currencyCode = currencyCode;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Money))
return false;
Money other = (Money)o;
boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
|| (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
return this.amount == other.amount
&& currencyCodeEquals;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + amount;
if (currencyCode != null) {
result = 31 * result + currencyCode.hashCode();
}
return result;
}
}

View File

@@ -1,39 +0,0 @@
package com.baeldung.equalshashcode;
class Team {
final String city;
final String department;
Team(String city, String department) {
this.city = city;
this.department = department;
}
@Override
public final boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Team))
return false;
Team otherTeam = (Team)o;
boolean cityEquals = (this.city == null && otherTeam.city == null)
|| this.city != null && this.city.equals(otherTeam.city);
boolean departmentEquals = (this.department == null && otherTeam.department == null)
|| this.department != null && this.department.equals(otherTeam.department);
return cityEquals && departmentEquals;
}
@Override
public final int hashCode() {
int result = 17;
if (city != null) {
result = 31 * result + city.hashCode();
}
if (department != null) {
result = 31 * result + department.hashCode();
}
return result;
}
}

View File

@@ -1,38 +0,0 @@
package com.baeldung.equalshashcode;
class Voucher {
private Money value;
private String store;
Voucher(int amount, String currencyCode, String store) {
this.value = new Money(amount, currencyCode);
this.store = store;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Voucher))
return false;
Voucher other = (Voucher)o;
boolean valueEquals = (this.value == null && other.value == null)
|| (this.value != null && this.value.equals(other.value));
boolean storeEquals = (this.store == null && other.store == null)
|| (this.store != null && this.store.equals(other.store));
return valueEquals && storeEquals;
}
@Override
public int hashCode() {
int result = 17;
if (this.value != null) {
result = 31 * result + value.hashCode();
}
if (this.store != null) {
result = 31 * result + store.hashCode();
}
return result;
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.equalshashcode;
/* (non-Javadoc)
* This class overrides equals, but it doesn't override hashCode.
*
* To see which problems this leads to:
* TeamUnitTest.givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue
*/
class WrongTeam {
String city;
String department;
WrongTeam(String city, String department) {
this.city = city;
this.department = department;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof WrongTeam))
return false;
WrongTeam otherTeam = (WrongTeam)o;
return this.city == otherTeam.city
&& this.department == otherTeam.department;
}
}

View File

@@ -1,47 +0,0 @@
package com.baeldung.equalshashcode;
/* (non-Javadoc)
* This class extends the Money class that has overridden the equals method and once again overrides the equals method.
*
* To see which problems this leads to:
* MoneyUnitTest.givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric
*/
class WrongVoucher extends Money {
private String store;
WrongVoucher(int amount, String currencyCode, String store) {
super(amount, currencyCode);
this.store = store;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof WrongVoucher))
return false;
WrongVoucher other = (WrongVoucher)o;
boolean currencyCodeEquals = (this.currencyCode == null && other.currencyCode == null)
|| (this.currencyCode != null && this.currencyCode.equals(other.currencyCode));
boolean storeEquals = (this.store == null && other.store == null)
|| (this.store != null && this.store.equals(other.store));
return this.amount == other.amount
&& currencyCodeEquals
&& storeEquals;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + amount;
if (this.currencyCode != null) {
result = 31 * result + currencyCode.hashCode();
}
if (this.store != null) {
result = 31 * result + store.hashCode();
}
return result;
}
}

View File

@@ -1,63 +0,0 @@
package com.baeldung.equalshashcode.entities;
import java.util.List;
import java.util.Set;
public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((genericList == null) ? 0 : genericList.hashCode());
result = prime * result + ((integerSet == null) ? 0 : integerSet.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof ComplexClass))
return false;
ComplexClass other = (ComplexClass) obj;
if (genericList == null) {
if (other.genericList != null)
return false;
} else if (!genericList.equals(other.genericList))
return false;
if (integerSet == null) {
if (other.integerSet != null)
return false;
} else if (!integerSet.equals(other.integerSet))
return false;
return true;
}
protected List<?> getGenericList() {
return genericList;
}
protected void setGenericArrayList(List<?> genericList) {
this.genericList = genericList;
}
protected Set<Integer> getIntegerSet() {
return integerSet;
}
protected void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
}

View File

@@ -1,54 +0,0 @@
package com.baeldung.equalshashcode.entities;
public class PrimitiveClass {
private boolean primitiveBoolean;
private int primitiveInt;
public PrimitiveClass(boolean primitiveBoolean, int primitiveInt) {
super();
this.primitiveBoolean = primitiveBoolean;
this.primitiveInt = primitiveInt;
}
protected boolean isPrimitiveBoolean() {
return primitiveBoolean;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (primitiveBoolean ? 1231 : 1237);
result = prime * result + primitiveInt;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrimitiveClass other = (PrimitiveClass) obj;
if (primitiveBoolean != other.primitiveBoolean)
return false;
if (primitiveInt != other.primitiveInt)
return false;
return true;
}
protected void setPrimitiveBoolean(boolean primitiveBoolean) {
this.primitiveBoolean = primitiveBoolean;
}
protected int getPrimitiveInt() {
return primitiveInt;
}
protected void setPrimitiveInt(int primitiveInt) {
this.primitiveInt = primitiveInt;
}
}

View File

@@ -1,58 +0,0 @@
package com.baeldung.equalshashcode.entities;
public class Rectangle extends Shape {
private double width;
private double length;
public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
@Override
public double area() {
return width * length;
}
@Override
public double perimeter() {
return 2 * (width + length);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(length);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(width);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Rectangle other = (Rectangle) obj;
if (Double.doubleToLongBits(length) != Double.doubleToLongBits(other.length))
return false;
if (Double.doubleToLongBits(width) != Double.doubleToLongBits(other.width))
return false;
return true;
}
protected double getWidth() {
return width;
}
protected double getLength() {
return length;
}
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.equalshashcode.entities;
public abstract class Shape {
public abstract double area();
public abstract double perimeter();
}

View File

@@ -1,58 +0,0 @@
package com.baeldung.equalshashcode.entities;
import java.awt.*;
public class Square extends Rectangle {
private Color color;
public Square(double width, Color color) {
super(width, width);
this.color = color;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((color == null) ? 0 : color.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof Square)) {
return false;
}
Square other = (Square) obj;
if (color == null) {
if (other.color != null) {
return false;
}
} else if (!color.equals(other.color)) {
return false;
}
return true;
}
protected Color getColor() {
return color;
}
protected void setColor(Color color) {
this.color = color;
}
}

View File

@@ -1,18 +0,0 @@
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);
}
}

View File

@@ -1,20 +0,0 @@
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;
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung.inheritancecomposition.application;
import com.baeldung.inheritancecomposition.model.Actress;
import com.baeldung.inheritancecomposition.model.Computer;
import com.baeldung.inheritancecomposition.model.StandardMemory;
import com.baeldung.inheritancecomposition.model.Person;
import com.baeldung.inheritancecomposition.model.StandardProcessor;
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
import com.baeldung.inheritancecomposition.model.Waitress;
public class Application {
public static void main(String[] args) {
Person person = new Person("John", "john@domain.com", 35);
Waitress waitress = new Waitress("Mary", "mary@domain.com", 22);
System.out.println(waitress.serveStarter("mixed salad"));
System.out.println(waitress.serveMainCourse("steak"));
System.out.println(waitress.serveDessert("cup of cofee"));
Actress actress = new Actress("Susan", "susan@domain.com", 30);
System.out.println(actress.readScript("Psycho"));
System.out.println(actress.performRole());
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
System.out.println(computer);
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class Actress extends Person {
public Actress(String name, String email, int age) {
super(name, email, age);
}
public String readScript(String movie) {
return "Reading the script of " + movie;
}
public String performRole() {
return "Performing a role";
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.inheritancecomposition.model;
import java.util.Optional;
public class Computer {
private Processor processor;
private Memory memory;
private SoundCard soundCard;
public Computer(Processor processor, Memory memory) {
this.processor = processor;
this.memory = memory;
}
public void setSoundCard(SoundCard soundCard) {
this.soundCard = soundCard;
}
public Processor getProcessor() {
return processor;
}
public Memory getMemory() {
return memory;
}
public Optional<SoundCard> getSoundCard() {
return Optional.ofNullable(soundCard);
}
@Override
public String toString() {
return "Computer{" + "processor=" + processor + ", memory=" + memory + ", soundcard=" + soundCard +"}";
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public interface Memory {
String getBrand();
String getSize();
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class Person {
private final String name;
private final String email;
private final int age;
public Person(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person{" + "name=" + name + ", email=" + email + ", age=" + age + "}";
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public interface Processor {
String getModel();
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public interface SoundCard {
String getBrand();
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class StandardMemory implements Memory {
private String brand;
private String size;
public StandardMemory(String brand, String size) {
this.brand = brand;
this.size = size;
}
public String getBrand() {
return brand;
}
public String getSize() {
return size;
}
@Override
public String toString() {
return "Memory{" + "brand=" + brand + ", size=" + size + "}";
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class StandardProcessor implements Processor {
private String model;
public StandardProcessor(String model) {
this.model = model;
}
@Override
public String getModel() {
return model;
}
@Override
public String toString() {
return "Processor{" + "model=" + model + "}";
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class StandardSoundCard implements SoundCard {
private String brand;
public StandardSoundCard(String brand) {
this.brand = brand;
}
@Override
public String getBrand() {
return brand;
}
@Override
public String toString() {
return "SoundCard{" + "brand=" + brand + "}";
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.inheritancecomposition.model;
public class Waitress extends Person {
public Waitress(String name, String email, int age) {
super(name, email, age);
}
public String serveStarter(String starter) {
return "Serving a " + starter;
}
public String serveMainCourse(String mainCourse) {
return "Serving a " + mainCourse;
}
public String serveDessert(String dessert) {
return "Serving a " + dessert;
}
}

View File

@@ -1,16 +0,0 @@
package com.baeldung.keyword;
import com.baeldung.keyword.superkeyword.SuperSub;
import com.baeldung.keyword.thiskeyword.KeywordUnitTest;
/**
* Created by Gebruiker on 5/14/2018.
*/
public class KeywordDemo {
public static void main(String[] args) {
KeywordUnitTest keyword = new KeywordUnitTest();
SuperSub child = new SuperSub("message from the child class");
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.keyword.superkeyword;
/**
* Created by Gebruiker on 5/14/2018.
*/
public class SuperBase {
String message = "super class";
public SuperBase() {
}
public SuperBase(String message) {
this.message = message;
}
public void printMessage() {
System.out.println(message);
}
}

View File

@@ -1,26 +0,0 @@
package com.baeldung.keyword.superkeyword;
/**
* Created by Gebruiker on 5/15/2018.
*/
public class SuperSub extends SuperBase {
String message = "child class";
public SuperSub(String message) {
super(message);
}
public SuperSub() {
super.printMessage();
printMessage();
}
public void getParentMessage() {
System.out.println(super.message);
}
public void printMessage() {
System.out.println(message);
}
}

View File

@@ -1,49 +0,0 @@
package com.baeldung.keyword.thiskeyword;
public class KeywordUnitTest {
private String name;
private int age;
public KeywordUnitTest() {
this("John", 27);
this.printMessage();
printInstance(this);
}
public KeywordUnitTest(String name, int age) {
this.name = name;
this.age = age;
}
public void printMessage() {
System.out.println("invoked by this");
}
public void printInstance(KeywordUnitTest thisKeyword) {
System.out.println(thisKeyword);
}
public KeywordUnitTest getCurrentInstance() {
return this;
}
class ThisInnerClass {
boolean isInnerClass = true;
public ThisInnerClass() {
KeywordUnitTest thisKeyword = KeywordUnitTest.this;
String outerString = KeywordUnitTest.this.name;
System.out.println(this.isInnerClass);
}
}
@Override
public String toString() {
return "KeywordTest{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

View File

@@ -1,5 +0,0 @@
package com.baeldung.markerinterface;
public interface DeletableShape extends Shape {
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.markerinterface;
public class Rectangle implements DeletableShape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getCircumference() {
return 2 * (width + height);
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.markerinterface;
public interface Shape {
double getArea();
double getCircumference();
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.markerinterface;
public class ShapeDao {
public boolean delete(Object object) {
if (!(object instanceof DeletableShape)) {
return false;
}
// Calling the code that deletes the entity from the database
return true;
}
}

View File

@@ -1,63 +0,0 @@
package com.baeldung.constructors;
import com.google.common.collect.Comparators;
import org.junit.Test;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
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,27 +0,0 @@
package com.baeldung.equalshashcode;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import org.junit.Test;
public class MoneyUnitTest {
@Test
public void givenMoneyInstancesWithSameAmountAndCurrency_whenEquals_thenReturnsTrue() {
Money income = new Money(55, "USD");
Money expenses = new Money(55, "USD");
assertTrue(income.equals(expenses));
}
@Test
public void givenMoneyAndVoucherInstances_whenEquals_thenReturnValuesArentSymmetric() {
Money cash = new Money(42, "USD");
WrongVoucher voucher = new WrongVoucher(42, "USD", "Amazon");
assertFalse(voucher.equals(cash));
assertTrue(cash.equals(voucher));
}
}

View File

@@ -1,46 +0,0 @@
package com.baeldung.equalshashcode;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
public class TeamUnitTest {
@Test
public void givenMapKeyWithHashCode_whenSearched_thenReturnsCorrectValue() {
Map<Team,String> leaders = new HashMap<>();
leaders.put(new Team("New York", "development"), "Anne");
leaders.put(new Team("Boston", "development"), "Brian");
leaders.put(new Team("Boston", "marketing"), "Charlie");
Team myTeam = new Team("New York", "development");
String myTeamleader = leaders.get(myTeam);
assertEquals("Anne", myTeamleader);
}
@Test
public void givenMapKeyWithoutHashCode_whenSearched_thenReturnsWrongValue() {
Map<WrongTeam,String> leaders = new HashMap<>();
leaders.put(new WrongTeam("New York", "development"), "Anne");
leaders.put(new WrongTeam("Boston", "development"), "Brian");
leaders.put(new WrongTeam("Boston", "marketing"), "Charlie");
WrongTeam myTeam = new WrongTeam("New York", "development");
String myTeamleader = leaders.get(myTeam);
assertFalse("Anne".equals(myTeamleader));
}
@Test
public void equalsContract() {
EqualsVerifier.forClass(Team.class).verify();
}
}

View File

@@ -1,35 +0,0 @@
package com.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.ComplexClass;
public class ComplexClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
List<String> strArrayList = new ArrayList<String>();
strArrayList.add("abc");
strArrayList.add("def");
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
List<String> strArrayListD = new ArrayList<String>();
strArrayListD.add("lmn");
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -1,23 +0,0 @@
package com.baeldung.equalshashcode.entities;
import org.junit.Assert;
import org.junit.Test;
public class PrimitiveClassUnitTest {
@Test
public void testTwoEqualsObjects() {
PrimitiveClass aObject = new PrimitiveClass(false, 2);
PrimitiveClass bObject = new PrimitiveClass(false, 2);
PrimitiveClass dObject = new PrimitiveClass(true, 2);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -1,27 +0,0 @@
package com.baeldung.equalshashcode.entities;
import java.awt.Color;
import org.junit.Assert;
import org.junit.Test;
import com.baeldung.equalshashcode.entities.Square;
public class SquareClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
Square aObject = new Square(10, Color.BLUE);
Square bObject = new Square(10, Color.BLUE);
Square dObject = new Square(20, Color.BLUE);
Assert.assertTrue(aObject.equals(bObject) && bObject.equals(aObject));
Assert.assertTrue(aObject.hashCode() == bObject.hashCode());
Assert.assertFalse(aObject.equals(dObject));
Assert.assertFalse(aObject.hashCode() == dObject.hashCode());
}
}

View File

@@ -1,36 +0,0 @@
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());
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Actress;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class ActressUnitTest {
private static Actress actress;
@BeforeClass
public static void setUpActressInstance() {
actress = new Actress("Susan", "susan@domain.com", 30);
}
@Test
public void givenActressInstance_whenCalledgetName_thenEqual() {
assertThat(actress.getName()).isEqualTo("Susan");
}
@Test
public void givenActressInstance_whenCalledgetEmail_thenEqual() {
assertThat(actress.getEmail()).isEqualTo("susan@domain.com");
}
@Test
public void givenActressInstance_whenCalledgetAge_thenEqual() {
assertThat(actress.getAge()).isEqualTo(30);
}
@Test
public void givenActressInstance_whenCalledreadScript_thenEqual() {
assertThat(actress.readScript("Psycho")).isEqualTo("Reading the script of Psycho");
}
@Test
public void givenActressInstance_whenCalledperfomRole_thenEqual() {
assertThat(actress.performRole()).isEqualTo("Performing a role");
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Computer;
import com.baeldung.inheritancecomposition.model.Memory;
import com.baeldung.inheritancecomposition.model.Processor;
import com.baeldung.inheritancecomposition.model.StandardMemory;
import com.baeldung.inheritancecomposition.model.StandardProcessor;
import com.baeldung.inheritancecomposition.model.StandardSoundCard;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class CompositionUnitTest {
@Test
public void givenComputerInstance_whenExtractedEachField_thenThreeAssertions() {
Computer computer = new Computer(new StandardProcessor("Intel I3"), new StandardMemory("Kingston", "1TB"));
computer.setSoundCard(new StandardSoundCard("Generic Sound Card"));
assertThat(computer.getProcessor()).isInstanceOf(Processor.class);
assertThat(computer.getMemory()).isInstanceOf(Memory.class);
assertThat(computer.getSoundCard()).isInstanceOf(Optional.class);
}
}

View File

@@ -1,20 +0,0 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Actress;
import com.baeldung.inheritancecomposition.model.Person;
import com.baeldung.inheritancecomposition.model.Waitress;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class InheritanceUnitTest {
@Test
public void givenWaitressInstance_whenCheckedType_thenIsInstanceOfPerson() {
assertThat(new Waitress("Mary", "mary@domain.com", 22)).isInstanceOf(Person.class);
}
@Test
public void givenActressInstance_whenCheckedType_thenIsInstanceOfPerson() {
assertThat(new Actress("Susan", "susan@domain.com", 30)).isInstanceOf(Person.class);
}
}

View File

@@ -1,31 +0,0 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Person;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class PersonUnitTest {
private static Person person;
@BeforeClass
public static void setPersonInstance() {
person = new Person("John", "john@domain.com", 35);
}
@Test
public void givenPersonInstance_whenCalledgetName_thenEqual() {
assertThat(person.getName()).isEqualTo("John");
}
@Test
public void givenPersonInstance_whenCalledgetEmail_thenEqual() {
assertThat(person.getEmail()).isEqualTo("john@domain.com");
}
@Test
public void givenPersonInstance_whenCalledgetAge_thenEqual() {
assertThat(person.getAge()).isEqualTo(35);
}
}

View File

@@ -1,46 +0,0 @@
package com.baeldung.inheritancecomposition.test;
import com.baeldung.inheritancecomposition.model.Waitress;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class WaitressUnitTest {
private static Waitress waitress;
@BeforeClass
public static void setUpWaitressInstance() {
waitress = new Waitress("Mary", "mary@domain.com", 22);
}
@Test
public void givenWaitressInstance_whenCalledgetName_thenOneAssertion() {
assertThat(waitress.getName()).isEqualTo("Mary");
}
@Test
public void givenWaitressInstance_whenCalledgetEmail_thenOneAssertion() {
assertThat(waitress.getEmail()).isEqualTo("mary@domain.com");
}
@Test
public void givenWaitressInstance_whenCalledgetAge_thenOneAssertion() {
assertThat(waitress.getAge()).isEqualTo(22);
}
@Test
public void givenWaitressInstance_whenCalledserveStarter_thenOneAssertion() {
assertThat(waitress.serveStarter("mixed salad")).isEqualTo("Serving a mixed salad");
}
@Test
public void givenWaitressInstance_whenCalledserveMainCourse_thenOneAssertion() {
assertThat(waitress.serveMainCourse("steak")).isEqualTo("Serving a steak");
}
@Test
public void givenWaitressInstance_whenCalledserveDessert_thenOneAssertion() {
assertThat(waitress.serveDessert("cup of coffee")).isEqualTo("Serving a cup of coffee");
}
}

View File

@@ -1,26 +0,0 @@
package com.baeldung.markerinterface;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MarkerInterfaceUnitTest {
@Test
public void givenDeletableObjectThenTrueReturned() {
ShapeDao shapeDao = new ShapeDao();
Object rectangle = new Rectangle(2, 3);
boolean result = shapeDao.delete(rectangle);
assertEquals(true, result);
}
@Test
public void givenNonDeletableObjectThenFalseReturned() {
ShapeDao shapeDao = new ShapeDao();
Object object = new Object();
boolean result = shapeDao.delete(object);
assertEquals(false, result);
}
}

View File

@@ -1,37 +0,0 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class NonPrimitivesUnitTest {
@Test
public void whenModifyingObjects_thenOriginalObjectChanged() {
Foo a = new Foo(1);
Foo b = new Foo(1);
// Before Modification
Assert.assertEquals(a.num, 1);
Assert.assertEquals(b.num, 1);
modify(a, b);
// After Modification
Assert.assertEquals(a.num, 2);
Assert.assertEquals(b.num, 1);
}
public static void modify(Foo a1, Foo b1) {
a1.num++;
b1 = new Foo(1);
b1.num++;
}
}
class Foo {
public int num;
public Foo(int num) {
this.num = num;
}
}

View File

@@ -1,28 +0,0 @@
package com.baeldung.parameterpassing;
import org.junit.Assert;
import org.junit.Test;
public class PrimitivesUnitTest {
@Test
public void whenModifyingPrimitives_thenOriginalValuesNotModified() {
int x = 1;
int y = 2;
// Before Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
modify(x, y);
// After Modification
Assert.assertEquals(x, 1);
Assert.assertEquals(y, 2);
}
public static void modify(int x1, int y1) {
x1 = 5;
y1 = 10;
}
}