This commit is contained in:
Jonathan Cook
2019-10-23 15:01:44 +02:00
parent db85c8f275
commit 684ec0d2e3
20486 changed files with 1642483 additions and 0 deletions
@@ -0,0 +1,26 @@
*.class
0.*
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
.resourceCache
# Packaged files #
*.jar
*.war
*.ear
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea/
*.iml
@@ -0,0 +1,16 @@
## Core Java Lang OOP
This module contains articles about Object-oriented programming (OOP) in Java
### Relevant Articles:
- [Guide to hashCode() in Java](https://www.baeldung.com/java-hashcode)
- [A Guide to the Static Keyword in Java](https://www.baeldung.com/java-static)
- [Polymorphism in Java](https://www.baeldung.com/java-polymorphism)
- [Method Overloading and Overriding in Java](https://www.baeldung.com/java-method-overload-override)
- [How to Make a Deep Copy of an Object in Java](https://www.baeldung.com/java-deep-copy)
- [Guide to Inheritance in Java](https://www.baeldung.com/java-inheritance)
- [Object Type Casting in Java](https://www.baeldung.com/java-type-casting)
- [The “final” Keyword in Java](https://www.baeldung.com/java-final)
- [Type Erasure in Java Explained](https://www.baeldung.com/java-type-erasure)
- [Variable and Method Hiding in Java](https://www.baeldung.com/java-variable-method-hiding)
- [[More -->]](/core-java-modules/core-java-lang-oop-2)
@@ -0,0 +1,59 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-lang-oop</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>core-java-lang-oop</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- web -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>core-java-lang-oop</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<properties>
<gson.version>2.8.2</gson.version>
<!-- testing -->
<assertj-core.version>3.10.0</assertj-core.version>
</properties>
</project>
@@ -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,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,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,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,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,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,137 @@
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_thenCopyShouldNotChange() {
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.");
}
@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,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,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,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,37 @@
package com.baeldung.initializationguide;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
import java.lang.reflect.InvocationTargetException;
public class UserUnitTest {
@Test
public void givenUserInstance_whenIntializedWithNew_thenInstanceIsNotNull() {
User user = new User("Alice", 1);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenInitializedWithReflection_thenInstanceIsNotNull() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
User user = User.class.getConstructor(String.class, int.class)
.newInstance("Alice", 2);
assertThat(user).isNotNull();
}
@Test
public void givenUserInstance_whenCopiedWithClone_thenExactMatchIsCreated() throws CloneNotSupportedException {
User user = new User("Alice", 3);
User clonedUser = (User) user.clone();
assertThat(clonedUser).isEqualTo(user);
}
@Test
public void givenUserInstance_whenValuesAreNotInitialized_thenUserNameAndIdReturnDefault() {
User user = new User();
assertThat(user.getName()).isNull();
assertThat(user.getId() == 0);
}
}
@@ -0,0 +1,41 @@
package com.baeldung.methodoverloadingoverriding.test;
import com.baeldung.methodoverloadingoverriding.util.Multiplier;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class MethodOverloadingUnitTest {
private static Multiplier multiplier;
@BeforeClass
public static void setUpMultiplierInstance() {
multiplier = new Multiplier();
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithTwoIntegers_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithTreeIntegers_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10, 10)).isEqualTo(1000);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithIntDouble_thenOneAssertion() {
assertThat(multiplier.multiply(10, 10.5)).isEqualTo(105.0);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithDoubleDouble_thenOneAssertion() {
assertThat(multiplier.multiply(10.5, 10.5)).isEqualTo(110.25);
}
@Test
public void givenMultiplierInstance_whenCalledMultiplyWithIntIntAndMatching_thenNoTypePromotion() {
assertThat(multiplier.multiply(10, 10)).isEqualTo(100);
}
}
@@ -0,0 +1,68 @@
package com.baeldung.methodoverloadingoverriding.test;
import com.baeldung.methodoverloadingoverriding.model.Car;
import com.baeldung.methodoverloadingoverriding.model.Vehicle;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class MethodOverridingUnitTest {
private static Vehicle vehicle;
private static Car car;
@BeforeClass
public static void setUpVehicleInstance() {
vehicle = new Vehicle();
}
@BeforeClass
public static void setUpCarInstance() {
car = new Car();
}
@Test
public void givenVehicleInstance_whenCalledAccelerate_thenOneAssertion() {
assertThat(vehicle.accelerate(100)).isEqualTo("The vehicle accelerates at : 100 MPH.");
}
@Test
public void givenVehicleInstance_whenCalledRun_thenOneAssertion() {
assertThat(vehicle.run()).isEqualTo("The vehicle is running.");
}
@Test
public void givenVehicleInstance_whenCalledStop_thenOneAssertion() {
assertThat(vehicle.stop()).isEqualTo("The vehicle has stopped.");
}
@Test
public void givenCarInstance_whenCalledAccelerate_thenOneAssertion() {
assertThat(car.accelerate(80)).isEqualTo("The car accelerates at : 80 MPH.");
}
@Test
public void givenCarInstance_whenCalledRun_thenOneAssertion() {
assertThat(car.run()).isEqualTo("The vehicle is running.");
}
@Test
public void givenCarInstance_whenCalledStop_thenOneAssertion() {
assertThat(car.stop()).isEqualTo("The vehicle has stopped.");
}
@Test
public void givenVehicleCarInstances_whenCalledAccelerateWithSameArgument_thenNotEqual() {
assertThat(vehicle.accelerate(100)).isNotEqualTo(car.accelerate(100));
}
@Test
public void givenVehicleCarInstances_whenCalledRun_thenEqual() {
assertThat(vehicle.run()).isEqualTo(car.run());
}
@Test
public void givenVehicleCarInstances_whenCalledStop_thenEqual() {
assertThat(vehicle.stop()).isEqualTo(car.stop());
}
}
@@ -0,0 +1,32 @@
package com.baeldung.polymorphism;
import static org.junit.Assert.*;
import java.awt.image.BufferedImage;
import org.junit.Test;
public class PolymorphismUnitTest {
@Test
public void givenImageFile_whenFileCreated_shouldSucceed() {
ImageFile imageFile = FileManager.createImageFile("SampleImageFile", 200, 100, new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB).toString()
.getBytes(), "v1.0.0");
assertEquals(200, imageFile.getHeight());
}
// Downcasting then Upcasting
@Test
public void givenTextFile_whenTextFileCreatedAndAssignedToGenericFileAndCastBackToTextFileOnGetWordCount_shouldSucceed() {
GenericFile textFile = FileManager.createTextFile("SampleTextFile", "This is a sample text content", "v1.0.0");
TextFile textFile2 = (TextFile) textFile;
assertEquals(6, textFile2.getWordCount());
}
// Downcasting
@Test(expected = ClassCastException.class)
public void givenGenericFile_whenCastToTextFileAndInvokeGetWordCount_shouldFail() {
GenericFile genericFile = new GenericFile();
TextFile textFile = (TextFile) genericFile;
System.out.println(textFile.getWordCount());
}
}
@@ -0,0 +1,14 @@
package com.baeldung.staticdemo;
import static org.junit.Assert.*;
import org.junit.Test;
public class CarIntegrationTest {
@Test
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
new Car("Jaguar", "V8");
new Car("Bugatti", "W16");
assertEquals(2, Car.numberOfCars);
}
}
@@ -0,0 +1,15 @@
package com.baeldung.staticdemo;
import org.junit.Assert;
import org.junit.Test;
public class SingletonIntegrationTest {
@Test
public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() {
Singleton object1 = Singleton.getInstance();
Singleton object2 = Singleton.getInstance();
Assert.assertSame(object1, object2);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.staticdemo;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.junit.Assert.assertThat;
import java.util.List;
import org.junit.Test;
public class StaticBlockIntegrationTest {
@Test
public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() {
List<String> actualList = StaticBlock.getRanks();
assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General"));
}
}
@@ -0,0 +1,21 @@
package com.baeldung.typeerasure;
import org.junit.Test;
public class TypeErasureUnitTest {
@Test(expected = ClassCastException.class)
public void givenIntegerStack_whenStringPushedAndAssignPoppedValueToInteger_shouldFail() {
IntegerStack integerStack = new IntegerStack(5);
Stack stack = integerStack;
stack.push("Hello");
Integer data = integerStack.pop();
}
@Test
public void givenAnyArray_whenInvokedPrintArray_shouldSucceed() {
Integer[] scores = new Integer[] { 100, 200, 10, 99, 20 };
ArrayContentPrintUtil.printArray(scores);
}
}
@@ -0,0 +1,13 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear