[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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()");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherPublic {
|
||||
public AnotherPublic() {
|
||||
SuperPublic.publicMethod(); // Available everywhere.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.accessmodifiers.another;
|
||||
|
||||
import com.baeldung.accessmodifiers.SuperPublic;
|
||||
|
||||
public class AnotherSuperPublic {
|
||||
public AnotherSuperPublic() {
|
||||
SuperPublic.publicMethod(); // Available everywhere. Let's note different package.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Animal.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("animal is eating");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeeder {
|
||||
|
||||
public void feed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
if (animal instanceof Cat) {
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void uncheckedFeed(List<Animal> animals) {
|
||||
animals.forEach(animal -> {
|
||||
animal.eat();
|
||||
((Cat) animal).meow();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AnimalFeederGeneric<T> {
|
||||
private Class<T> type;
|
||||
|
||||
public AnimalFeederGeneric(Class<T> type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public List<T> feed(List<Animal> animals) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
animals.forEach(animal -> {
|
||||
if (type.isInstance(animal)) {
|
||||
T objAsType = type.cast(animal);
|
||||
list.add(objAsType);
|
||||
}
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Cat extends Animal implements Mew {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Cat.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("cat is eating");
|
||||
}
|
||||
|
||||
public void meow() {
|
||||
LOGGER.info("meow");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class Dog extends Animal {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(Dog.class);
|
||||
|
||||
public void eat() {
|
||||
LOGGER.info("dog is eating");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
public interface Mew {
|
||||
public void meow();
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class Address implements Serializable, Cloneable {
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
try {
|
||||
return (Address) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
return new Address(this.street, this.getCity(), this.getCountry());
|
||||
}
|
||||
}
|
||||
|
||||
private static final long serialVersionUID = 1740913841244949416L;
|
||||
private String street;
|
||||
private String city;
|
||||
|
||||
private String country;
|
||||
|
||||
public Address(Address that) {
|
||||
this(that.getStreet(), that.getCity(), that.getCountry());
|
||||
}
|
||||
|
||||
public Address(String street, String city, String country) {
|
||||
this.street = street;
|
||||
this.city = city;
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public Address() {
|
||||
}
|
||||
|
||||
public String getStreet() {
|
||||
return street;
|
||||
}
|
||||
|
||||
public String getCity() {
|
||||
return city;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setStreet(String street) {
|
||||
this.street = street;
|
||||
}
|
||||
|
||||
public void setCity(String city) {
|
||||
this.city = city;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
|
||||
private static final long serialVersionUID = -3427002229954777557L;
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
private Address address;
|
||||
|
||||
public User(String firstName, String lastName, Address address) {
|
||||
this.firstName = firstName;
|
||||
this.lastName = lastName;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public User(User that) {
|
||||
this(that.getFirstName(), that.getLastName(), new Address(that.getAddress()));
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object clone() {
|
||||
User user;
|
||||
try {
|
||||
user = (User) super.clone();
|
||||
} catch (CloneNotSupportedException e) {
|
||||
user = new User(this.getFirstName(), this.getLastName(), this.getAddress());
|
||||
}
|
||||
user.address = (Address) this.address.clone();
|
||||
return user;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public Address getAddress() {
|
||||
return address;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.equalshashcode.entities;
|
||||
|
||||
public abstract class Shape {
|
||||
public abstract double area();
|
||||
|
||||
public abstract double perimeter();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackCat {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class BlackDog extends Dog {
|
||||
// public void sound() {
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public final class Cat {
|
||||
|
||||
private int weight;
|
||||
|
||||
public int getWeight() {
|
||||
return weight;
|
||||
}
|
||||
|
||||
public void setWeight(int weight) {
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public void methodWithFinalArguments(final int x) {
|
||||
// x=1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
public class Dog {
|
||||
|
||||
public final void sound() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.hashcode.entities;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class User {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(User.class);
|
||||
private long id;
|
||||
private String name;
|
||||
private String email;
|
||||
|
||||
public User(long id, String name, String email) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (o == null)
|
||||
return false;
|
||||
if (this.getClass() != o.getClass())
|
||||
return false;
|
||||
User user = (User) o;
|
||||
return id == user.id && (name.equals(user.name) && email.equals(user.email));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hash = 7;
|
||||
hash = 31 * hash + (int) id;
|
||||
hash = 31 * hash + (name == null ? 0 : name.hashCode());
|
||||
hash = 31 * hash + (email == null ? 0 : email.hashCode());
|
||||
logger.info("hashCode() method called - Computed hash: " + hash);
|
||||
return hash;
|
||||
}
|
||||
// getters and setters here
|
||||
|
||||
}
|
||||
@@ -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,43 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class ArmoredCar extends Car implements Floatable, Flyable{
|
||||
private int bulletProofWindows;
|
||||
private String model;
|
||||
|
||||
public void remoteStartCar() {
|
||||
// this vehicle can be started by using a remote control
|
||||
}
|
||||
|
||||
public String registerModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public String getAValue() {
|
||||
return super.model; // returns value of model defined in base class Car
|
||||
// return this.model; // will return value of model defined in ArmoredCar
|
||||
// return model; // will return value of model defined in ArmoredCar
|
||||
}
|
||||
|
||||
public static String msg() {
|
||||
// return super.msg(); // this won't compile.
|
||||
return "ArmoredCar";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("I can float!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("I can fly!");
|
||||
}
|
||||
|
||||
public void aMethod() {
|
||||
// System.out.println(duration); // Won't compile
|
||||
System.out.println(Floatable.duration); // outputs 10
|
||||
System.out.println(Flyable.duration); // outputs 20
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class BMW extends Car {
|
||||
public BMW() {
|
||||
super(5, "BMW");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Car {
|
||||
private final int DEFAULT_WHEEL_COUNT = 5;
|
||||
private final String DEFAULT_MODEL = "Basic";
|
||||
|
||||
protected int wheels;
|
||||
protected String model;
|
||||
|
||||
public Car() {
|
||||
this.wheels = DEFAULT_WHEEL_COUNT;
|
||||
this.model = DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
public Car(int wheels, String model) {
|
||||
this.wheels = wheels;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
// Check essential parts
|
||||
// If okay, start.
|
||||
}
|
||||
public static int count = 10;
|
||||
public static String msg() {
|
||||
return "Car";
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return model;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class Employee {
|
||||
private String name;
|
||||
private Car car;
|
||||
|
||||
public Employee(String name, Car car) {
|
||||
this.name = name;
|
||||
this.car = car;
|
||||
}
|
||||
|
||||
public Car getCar() {
|
||||
return car;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Floatable {
|
||||
int duration = 10;
|
||||
void floatOnWater();
|
||||
|
||||
default void repair() {
|
||||
System.out.println("Repairing Floatable object");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface Flyable {
|
||||
int duration = 10;
|
||||
void fly();
|
||||
|
||||
/*
|
||||
* Commented
|
||||
*/
|
||||
//default void repair() {
|
||||
// System.out.println("Repairing Flyable object");
|
||||
//}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public class SpaceCar extends Car implements SpaceTraveller {
|
||||
@Override
|
||||
public void floatOnWater() {
|
||||
System.out.println("SpaceCar floating!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void fly() {
|
||||
System.out.println("SpaceCar flying!");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remoteControl() {
|
||||
System.out.println("SpaceCar being controlled remotely!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
public interface SpaceTraveller extends Floatable, Flyable {
|
||||
int duration = 10;
|
||||
void remoteControl();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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 +"}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Memory {
|
||||
|
||||
String getBrand();
|
||||
|
||||
String getSize();
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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 + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface Processor {
|
||||
|
||||
String getModel();
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.inheritancecomposition.model;
|
||||
|
||||
public interface SoundCard {
|
||||
|
||||
String getBrand();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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 + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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 + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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 + "}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.initializationguide;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
public class User implements Serializable, Cloneable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
static String forum;
|
||||
private String name;
|
||||
private int id;
|
||||
|
||||
{
|
||||
id = 0;
|
||||
System.out.println("Instance Initializer");
|
||||
}
|
||||
|
||||
static {
|
||||
forum = "Java";
|
||||
System.out.println("Static Initializer");
|
||||
}
|
||||
|
||||
public User(String name, int id) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User() {
|
||||
System.out.println("Constructor");
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object clone() throws CloneNotSupportedException {
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
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 +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.markerinterface;
|
||||
|
||||
public interface DeletableShape extends Shape {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.markerinterface;
|
||||
|
||||
public interface Shape {
|
||||
double getArea();
|
||||
double getCircumference();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.methodoverloadingoverriding.application;
|
||||
|
||||
import com.baeldung.methodoverloadingoverriding.model.Car;
|
||||
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
|
||||
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
|
||||
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Multiplier multiplier = new Multiplier();
|
||||
System.out.println(multiplier.multiply(10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10, 10));
|
||||
System.out.println(multiplier.multiply(10, 10.5));
|
||||
System.out.println(multiplier.multiply(10.5, 10.5));
|
||||
|
||||
Vehicle vehicle = new Vehicle();
|
||||
System.out.println(vehicle.accelerate(100));
|
||||
System.out.println(vehicle.run());
|
||||
System.out.println(vehicle.stop());
|
||||
|
||||
Vehicle car = new Car();
|
||||
System.out.println(car.accelerate(80));
|
||||
System.out.println(car.run());
|
||||
System.out.println(car.stop());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Car extends Vehicle {
|
||||
|
||||
@Override
|
||||
public String accelerate(long mph) {
|
||||
return "The car accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.model;
|
||||
|
||||
public class Vehicle {
|
||||
|
||||
public String accelerate(long mph) {
|
||||
return "The vehicle accelerates at : " + mph + " MPH.";
|
||||
}
|
||||
|
||||
public String stop() {
|
||||
return "The vehicle has stopped.";
|
||||
}
|
||||
|
||||
public String run() {
|
||||
return "The vehicle is running.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.methodoverloadingoverriding.util;
|
||||
|
||||
public class Multiplier {
|
||||
|
||||
public int multiply(int a, int b) {
|
||||
return a * b;
|
||||
}
|
||||
|
||||
public int multiply(int a, int b, int c) {
|
||||
return a * b * c;
|
||||
}
|
||||
|
||||
public double multiply(double a, double b) {
|
||||
return a * b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileManager {
|
||||
|
||||
final static Logger logger = LoggerFactory.getLogger(FileManager.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
GenericFile file1 = new TextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
|
||||
logger.info("File Info: \n" + file1.getFileInfo() + "\n");
|
||||
ImageFile imageFile = new ImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
|
||||
.getBytes(), "v1.0.0");
|
||||
logger.info("File Info: \n" + imageFile.getFileInfo());
|
||||
}
|
||||
|
||||
public static ImageFile createImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
ImageFile imageFile = new ImageFile(name, height, width, content, version);
|
||||
logger.info("File 2 Info: \n" + imageFile.getFileInfo());
|
||||
return imageFile;
|
||||
}
|
||||
|
||||
public static GenericFile createTextFile(String name, String content, String version) {
|
||||
GenericFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
public static TextFile createTextFile2(String name, String content, String version) {
|
||||
TextFile file1 = new TextFile(name, content, version);
|
||||
logger.info("File 1 Info: \n" + file1.getFileInfo() + "\n");
|
||||
return file1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class GenericFile {
|
||||
private String name;
|
||||
private String extension;
|
||||
private Date dateCreated;
|
||||
private String version;
|
||||
private byte[] content;
|
||||
|
||||
public GenericFile() {
|
||||
this.setDateCreated(new Date());
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getExtension() {
|
||||
return extension;
|
||||
}
|
||||
|
||||
public void setExtension(String extension) {
|
||||
this.extension = extension;
|
||||
}
|
||||
|
||||
public Date getDateCreated() {
|
||||
return dateCreated;
|
||||
}
|
||||
|
||||
public void setDateCreated(Date dateCreated) {
|
||||
this.dateCreated = dateCreated;
|
||||
}
|
||||
|
||||
public String getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(String version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public byte[] getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(byte[] content) {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Generic File Impl";
|
||||
}
|
||||
|
||||
public Object read() {
|
||||
return content;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
public class ImageFile extends GenericFile {
|
||||
private int height;
|
||||
private int width;
|
||||
|
||||
public ImageFile(String name, int height, int width, byte[] content, String version) {
|
||||
this.setHeight(height);
|
||||
this.setWidth(width);
|
||||
this.setContent(content);
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".jpg");
|
||||
}
|
||||
|
||||
public int getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(int height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(int width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Image File Impl";
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.polymorphism;
|
||||
|
||||
public class TextFile extends GenericFile {
|
||||
private int wordCount;
|
||||
|
||||
public TextFile(String name, String content, String version) {
|
||||
String[] words = content.split(" ");
|
||||
this.setWordCount(words.length > 0 ? words.length : 1);
|
||||
this.setContent(content.getBytes());
|
||||
this.setName(name);
|
||||
this.setVersion(version);
|
||||
this.setExtension(".txt");
|
||||
}
|
||||
|
||||
public int getWordCount() {
|
||||
return wordCount;
|
||||
}
|
||||
|
||||
public void setWordCount(int wordCount) {
|
||||
this.wordCount = wordCount;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return "Text File Impl";
|
||||
}
|
||||
|
||||
public String read() {
|
||||
return this.getContent()
|
||||
.toString();
|
||||
}
|
||||
|
||||
public String read(int limit) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(0, limit);
|
||||
}
|
||||
|
||||
public String read(int start, int stop) {
|
||||
return this.getContent()
|
||||
.toString()
|
||||
.substring(start, stop);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.scope.method;
|
||||
|
||||
|
||||
public class BaseMethodClass {
|
||||
|
||||
public static void printMessage() {
|
||||
System.out.println("base static method");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.scope.method;
|
||||
|
||||
|
||||
public class ChildMethodClass extends BaseMethodClass {
|
||||
|
||||
public static void printMessage() {
|
||||
System.out.println("child static method");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.scope.method;
|
||||
|
||||
public class MethodHidingDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ChildMethodClass.printMessage();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.scope.variable;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 5/7/2018.
|
||||
*/
|
||||
public class ChildVariable extends ParentVariable {
|
||||
|
||||
String instanceVariable = "child variable";
|
||||
|
||||
public void printInstanceVariable() {
|
||||
System.out.println(instanceVariable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.scope.variable;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 5/6/2018.
|
||||
*/
|
||||
public class HideVariable {
|
||||
|
||||
private String message = "this is instance variable";
|
||||
|
||||
HideVariable() {
|
||||
String message = "constructor local variable";
|
||||
System.out.println(message);
|
||||
}
|
||||
|
||||
public void printLocalVariable() {
|
||||
String message = "method local variable";
|
||||
System.out.println(message);
|
||||
}
|
||||
|
||||
public void printInstanceVariable() {
|
||||
System.out.println(this.message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.scope.variable;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 5/7/2018.
|
||||
*/
|
||||
public class ParentVariable {
|
||||
|
||||
String instanceVariable = "parent variable";
|
||||
|
||||
public void printInstanceVariable() {
|
||||
System.out.println(instanceVariable);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.scope.variable;
|
||||
|
||||
/**
|
||||
* Created by Gebruiker on 5/6/2018.
|
||||
*/
|
||||
public class VariableHidingDemo {
|
||||
public static void main(String[] args) {
|
||||
HideVariable variable = new HideVariable();
|
||||
variable.printLocalVariable();
|
||||
variable.printInstanceVariable();
|
||||
|
||||
ParentVariable parentVariable = new ParentVariable();
|
||||
ParentVariable childVariable = new ChildVariable();
|
||||
|
||||
parentVariable.printInstanceVariable();
|
||||
childVariable.printInstanceVariable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.baeldung.staticdemo;
|
||||
|
||||
/**
|
||||
* This class demonstrates the use of static fields and static methods
|
||||
* the instance variables engine and displacement are distinct for
|
||||
* each and every object whereas static/class variable numberOfCars
|
||||
* is unique and is shared across all objects of this class.
|
||||
*
|
||||
* @author baeldung
|
||||
*
|
||||
*/
|
||||
public class Car {
|
||||
private String name;
|
||||
private String engine;
|
||||
|
||||
public static int numberOfCars;
|
||||
|
||||
public Car(String name, String engine) {
|
||||
this.name = name;
|
||||
this.engine = engine;
|
||||
numberOfCars++;
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
public static int getNumberOfCars() {
|
||||
return numberOfCars;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
public void setEngine(String engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
public static void setNumberOfCars(int numberOfCars) {
|
||||
Car.numberOfCars = numberOfCars;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.staticdemo;
|
||||
|
||||
public class Singleton {
|
||||
private Singleton() {}
|
||||
|
||||
private static class SingletonHolder {
|
||||
public static final Singleton instance = new Singleton();
|
||||
}
|
||||
|
||||
public static Singleton getInstance() {
|
||||
return SingletonHolder.instance;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.staticdemo;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class StaticBlock {
|
||||
private static List<String> ranks = new LinkedList<>();
|
||||
|
||||
static {
|
||||
ranks.add("Lieutenant");
|
||||
ranks.add("Captain");
|
||||
ranks.add("Major");
|
||||
}
|
||||
|
||||
static {
|
||||
ranks.add("Colonel");
|
||||
ranks.add("General");
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
public static List<String> getRanks() {
|
||||
return ranks;
|
||||
}
|
||||
|
||||
public static void setRanks(List<String> ranks) {
|
||||
StaticBlock.ranks = ranks;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
public class ArrayContentPrintUtil {
|
||||
|
||||
public static <E> void printArray(E[] array) {
|
||||
for (E element : array) {
|
||||
System.out.printf("%s ", element);
|
||||
}
|
||||
}
|
||||
|
||||
public static <E extends Comparable<E>> void printArray(E[] array) {
|
||||
for (E element : array) {
|
||||
System.out.printf("%s ", element);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class BoundStack<E extends Comparable<E>> {
|
||||
|
||||
private E[] stackContent;
|
||||
private int total;
|
||||
|
||||
public BoundStack(int capacity) {
|
||||
this.stackContent = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
public void push(E data) {
|
||||
if (total == stackContent.length) {
|
||||
resize(2 * stackContent.length);
|
||||
}
|
||||
stackContent[total++] = data;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (!isEmpty()) {
|
||||
E datum = stackContent[total];
|
||||
stackContent[total--] = null;
|
||||
return datum;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void resize(int capacity) {
|
||||
Arrays.copyOf(stackContent, capacity);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return total == 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
public class IntegerStack extends Stack<Integer> {
|
||||
|
||||
public IntegerStack(int capacity) {
|
||||
super(capacity);
|
||||
}
|
||||
|
||||
public void push(Integer value) {
|
||||
System.out.println("Pushing into my integerStack");
|
||||
super.push(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.typeerasure;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class Stack<E> {
|
||||
|
||||
private E[] stackContent;
|
||||
private int total;
|
||||
|
||||
public Stack(int capacity) {
|
||||
this.stackContent = (E[]) new Object[capacity];
|
||||
}
|
||||
|
||||
public void push(E data) {
|
||||
System.out.println("In base stack push#");
|
||||
if (total == stackContent.length) {
|
||||
resize(2 * stackContent.length);
|
||||
}
|
||||
stackContent[total++] = data;
|
||||
}
|
||||
|
||||
public E pop() {
|
||||
if (!isEmpty()) {
|
||||
E datum = stackContent[total];
|
||||
stackContent[total--] = null;
|
||||
return datum;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void resize(int capacity) {
|
||||
Arrays.copyOf(stackContent, capacity);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return total == 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.casting;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class CastingUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPrimitiveConverted_thenValueChanged() {
|
||||
double myDouble = 1.1;
|
||||
int myInt = (int) myDouble;
|
||||
|
||||
assertNotEquals(myDouble, myInt);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcast_thenInstanceUnchanged() {
|
||||
Cat cat = new Cat();
|
||||
Animal animal = cat;
|
||||
animal = (Animal) cat;
|
||||
assertTrue(animal instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToObject_thenInstanceUnchanged() {
|
||||
Object object = new Animal();
|
||||
assertTrue(object instanceof Animal);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToInterface_thenInstanceUnchanged() {
|
||||
Mew mew = new Cat();
|
||||
assertTrue(mew instanceof Cat);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUpcastToAnimal_thenOverridenMethodsCalled() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().feed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCat_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
((Cat) animal).meow();
|
||||
}
|
||||
|
||||
@Test(expected = ClassCastException.class)
|
||||
public void whenDownCastWithoutCheck_thenExceptionThrown() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
new AnimalFeeder().uncheckedFeed(animals);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
|
||||
Animal animal = new Cat();
|
||||
if (Cat.class.isInstance(animal)) {
|
||||
Cat cat = Cat.class.cast(animal);
|
||||
cat.meow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenParameterCat_thenOnlyCatsFed() {
|
||||
List<Animal> animals = new ArrayList<>();
|
||||
animals.add(new Cat());
|
||||
animals.add(new Dog());
|
||||
AnimalFeederGeneric<Cat> catFeeder = new AnimalFeederGeneric<Cat>(Cat.class);
|
||||
List<Cat> fedAnimals = catFeeder.feed(animals);
|
||||
|
||||
assertTrue(fedAnimals.size() == 1);
|
||||
assertTrue(fedAnimals.get(0) instanceof Cat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.constructors;
|
||||
|
||||
import com.baeldung.constructors.*;
|
||||
|
||||
import java.util.logging.Logger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.Month;
|
||||
|
||||
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;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.commons.lang3.SerializationUtils;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
public class DeepCopyUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingDeepCopyWithCopyConstructor_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
assertThat(deepCopy).isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenConstructorCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = new User(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCloneCopyShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) pm.clone();
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCommonsCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User deepCopy = (User) SerializationUtils.clone(pm);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenGsonCloneShouldNotChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
Gson gson = new Gson();
|
||||
User deepCopy = gson.fromJson(gson.toJson(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenJacksonCopyShouldNotChange() throws IOException {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
User deepCopy = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(deepCopy.getAddress().getCountry()).isNotEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Ignore
|
||||
public void whenMakingCopies_thenShowHowLongEachMethodTakes() throws CloneNotSupportedException, IOException {
|
||||
int times = 1000000;
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
long start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) SerializationUtils.clone(pm);
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Apache Commons Lang took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
Gson gson = new Gson();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = gson.fromJson(gson.toJson(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Gson took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = new User(pm);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with the copy constructor took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = (User) pm.clone();
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Cloneable interface took " + (end - start) + " milliseconds.");
|
||||
|
||||
start = System.currentTimeMillis();
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
for (int i = 0; i < times; i++) {
|
||||
User primeMinisterClone = objectMapper.readValue(objectMapper.writeValueAsString(pm), User.class);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("Cloning with Jackson took " + (end - start) + " milliseconds.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.deepcopy;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ShallowCopyUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenShallowCopying_thenObjectsShouldNotBeSame() {
|
||||
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
assertThat(shallowCopy)
|
||||
.isNotSameAs(pm);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenModifyingOriginalObject_thenCopyShouldChange() {
|
||||
Address address = new Address("Downing St 10", "London", "England");
|
||||
User pm = new User("Prime", "Minister", address);
|
||||
User shallowCopy = new User(pm.getFirstName(), pm.getLastName(), pm.getAddress());
|
||||
|
||||
address.setCountry("Great Britain");
|
||||
|
||||
assertThat(shallowCopy.getAddress().getCountry())
|
||||
.isEqualTo(pm.getAddress().getCountry());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.finalkeyword;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FinalUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalClassProperties_thenChanged() {
|
||||
Cat cat = new Cat();
|
||||
cat.setWeight(1);
|
||||
|
||||
assertEquals(1, cat.getWeight());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFinalVariableAssign_thenOnlyOnce() {
|
||||
final int i;
|
||||
i = 1;
|
||||
// i=2;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenChangedFinalReference_thenChanged() {
|
||||
|
||||
final Cat cat = new Cat();
|
||||
// cat=new Cat();
|
||||
cat.setWeight(5);
|
||||
|
||||
assertEquals(5, cat.getWeight());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.hashcode.application;
|
||||
|
||||
import com.baeldung.hashcode.entities.User;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class ApplicationUnitTest {
|
||||
|
||||
@Test
|
||||
public void main_NoInputState_TextPrintedToConsole() throws Exception {
|
||||
Map<User, User> users = new HashMap<>();
|
||||
User user1 = new User(1L, "John", "john@domain.com");
|
||||
User user2 = new User(2L, "Jennifer", "jennifer@domain.com");
|
||||
User user3 = new User(3L, "Mary", "mary@domain.com");
|
||||
|
||||
users.put(user1, user1);
|
||||
users.put(user2, user2);
|
||||
users.put(user3, user3);
|
||||
|
||||
assertTrue(users.containsKey(user1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.hashcode.entities;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class UserUnitTest {
|
||||
|
||||
private User user;
|
||||
private User comparisonUser;
|
||||
|
||||
@Before
|
||||
public void setUpUserInstances() {
|
||||
this.user = new User(1L, "test", "test@domain.com");
|
||||
this.comparisonUser = this.user;
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDownUserInstances() {
|
||||
user = null;
|
||||
comparisonUser = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void equals_EqualUserInstance_TrueAssertion() {
|
||||
Assert.assertTrue(user.equals(comparisonUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void hashCode_UserHash_TrueAssertion() {
|
||||
Assert.assertEquals(1792276941, user.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.baeldung.inheritance;
|
||||
|
||||
import com.baeldung.inheritance.*;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
public class AppUnitTest extends TestCase {
|
||||
|
||||
public AppUnitTest(String testName) {
|
||||
super( testName );
|
||||
}
|
||||
|
||||
public static Test suite() {
|
||||
return new TestSuite(AppUnitTest.class);
|
||||
}
|
||||
|
||||
@SuppressWarnings("static-access")
|
||||
public void testStaticMethodUsingBaseClassVariable() {
|
||||
Car first = new ArmoredCar();
|
||||
assertEquals("Car", first.msg());
|
||||
}
|
||||
|
||||
@SuppressWarnings("static-access")
|
||||
public void testStaticMethodUsingDerivedClassVariable() {
|
||||
ArmoredCar second = new ArmoredCar();
|
||||
assertEquals("ArmoredCar", second.msg());
|
||||
}
|
||||
|
||||
public void testAssignArmoredCarToCar() {
|
||||
Employee e1 = new Employee("Shreya", new ArmoredCar());
|
||||
assertNotNull(e1.getCar());
|
||||
}
|
||||
|
||||
public void testAssignSpaceCarToCar() {
|
||||
Employee e2 = new Employee("Paul", new SpaceCar());
|
||||
assertNotNull(e2.getCar());
|
||||
}
|
||||
|
||||
public void testBMWToCar() {
|
||||
Employee e3 = new Employee("Pavni", new BMW());
|
||||
assertNotNull(e3.getCar());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user