[JAVA-621] Flattened modules hierarchy

This commit is contained in:
dupirefr
2020-04-07 21:28:45 +02:00
parent 635ecae691
commit 42b0086080
210 changed files with 24 additions and 44 deletions

View File

@@ -0,0 +1,29 @@
package com.baeldung.abstractclasses.application;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Application {
public static void main(String[] args) throws IOException, URISyntaxException {
Application application = new Application();
Path path = application.getPathFromResourcesFile("files/test.txt");
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
lowercaseFileReader.readFile().forEach(line -> System.out.println(line));
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
uppercaseFileReader.readFile().forEach(line -> System.out.println(line));
}
private Path getPathFromResourcesFile(String filePath) throws URISyntaxException {
return Paths.get(getClass().getClassLoader().getResource(filePath).toURI());
}
}

View File

@@ -0,0 +1,27 @@
package com.baeldung.abstractclasses.filereaders;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
public abstract class BaseFileReader {
protected Path filePath;
protected BaseFileReader(Path filePath) {
this.filePath = filePath;
}
public Path getFilePath() {
return filePath;
}
public List<String> readFile() throws IOException {
return Files.lines(filePath)
.map(this::mapFileLine).collect(Collectors.toList());
}
protected abstract String mapFileLine(String line);
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
import java.nio.file.Path;
public class LowercaseFileReader extends BaseFileReader {
public LowercaseFileReader(Path filePath) {
super(filePath);
}
@Override
public String mapFileLine(String line) {
return line.toLowerCase();
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.abstractclasses.filereaders;
import java.nio.file.Path;
public class UppercaseFileReader extends BaseFileReader {
public UppercaseFileReader(Path filePath) {
super(filePath);
}
@Override
public String mapFileLine(String line) {
return line.toUpperCase();
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.anonymous;
public class Book {
final String title;
public Book(String title) {
this.title = title;
}
public String description() {
return "Title: " + title;
}
}

View File

@@ -0,0 +1,64 @@
package com.baeldung.anonymous;
import java.util.ArrayList;
import java.util.List;
/**
* Code snippet that illustrates the usage of anonymous classes.
*
* Note that use of Runnable instances in this example does not demonstrate their
* common use.
*
* @author A. Shcherbakov
*
*/
public class Main {
public static void main(String[] args) {
final List<Runnable> actions = new ArrayList<Runnable>(2);
Runnable action = new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable.");
}
};
actions.add(action);
Book book = new Book("Design Patterns") {
@Override
public String description() {
return "Famous GoF book.";
}
};
System.out.println(String.format("Title: %s, description: %s", book.title, book.description()));
actions.add(new Runnable() {
@Override
public void run() {
System.out.println("Hello from runnable #2.");
}
});
int count = 1;
Runnable action2 = new Runnable() {
static final int x = 0;
// static int y = 0;
@Override
public void run() {
System.out.println(String.format("Runnable with captured variables: count = %s, x = %s", count, x));
}
};
actions.add(action2);
for (Runnable a : actions) {
a.run();
}
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,5 @@
package com.baeldung.casting;
public interface Mew {
public void meow();
}

View File

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

View File

@@ -0,0 +1,12 @@
package com.baeldung.inheritance;
public class BMW extends Car {
public BMW() {
super(5, "BMW");
}
@Override
public String toString() {
return model;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,6 @@
package com.baeldung.inheritance;
public interface SpaceTraveller extends Floatable, Flyable {
int duration = 10;
void remoteControl();
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.innerinterfaces;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CommaSeparatedCustomers implements Customer.List {
private List<Customer> customers = new ArrayList<Customer>();
@Override
public void Add(Customer customer) {
customers.add(customer);
}
@Override
public String getCustomerNames() {
return customers.stream().map(customer -> customer.getName()).collect(Collectors.joining(","));
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.innerinterfaces;
public class Customer {
public interface List {
void Add(Customer customer);
String getCustomerNames();
}
private String name;
public Customer(String name) {
this.name = name;
}
String getName() {
return name;
}
}

View File

@@ -0,0 +1,5 @@
package com.baeldung.interfaces;
public interface Box extends HasColor {
int getHeight();
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.interfaces;
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.interfaces;
import java.util.Comparator;
public class EmployeeSalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee employeeA, Employee employeeB) {
if (employeeA.getSalary() < employeeB.getSalary()) {
return -1;
} else if (employeeA.getSalary() > employeeB.getSalary()) {
return 1;
} else {
return 0;
}
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.interfaces;
public interface HasColor {
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.interfaces.multiinheritance;
public class Car implements Fly,Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.interfaces.multiinheritance;
public interface Fly {
void fly();
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
default void printSpecs(){
System.out.println("Transform Specification");
}
}

View File

@@ -0,0 +1,4 @@
package com.baeldung.interfaces.multiinheritance;
public abstract class Vehicle implements Transform {
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
@Override
public String name() {
return "Circle";
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
import java.util.List;
public class MainTestClass {
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
Shape circleShape = new Circle();
Shape squareShape = new Square();
shapes.add(circleShape);
shapes.add(squareShape);
for (Shape shape : shapes) {
System.out.println(shape.name());
}
}
}

View File

@@ -0,0 +1,6 @@
package com.baeldung.interfaces.polymorphysim;
public interface Shape {
String name();
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
@Override
public String name() {
return "Square";
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,9 @@
package com.baeldung.scope.method;
public class BaseMethodClass {
public static void printMessage() {
System.out.println("base static method");
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.scope.method;
public class ChildMethodClass extends BaseMethodClass {
public static void printMessage() {
System.out.println("child static method");
}
}

View File

@@ -0,0 +1,8 @@
package com.baeldung.scope.method;
public class MethodHidingDemo {
public static void main(String[] args) {
ChildMethodClass.printMessage();
}
}

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,10 @@
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10

View File

@@ -0,0 +1,20 @@
package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.LowercaseFileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class LowercaseFileReaderUnitTest {
@Test
public void givenLowercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
BaseFileReader lowercaseFileReader = new LowercaseFileReader(path);
assertThat(lowercaseFileReader.readFile()).isInstanceOf(List.class);
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.abstractclasses.test;
import com.baeldung.abstractclasses.filereaders.BaseFileReader;
import com.baeldung.abstractclasses.filereaders.UppercaseFileReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class UppercaseFileReaderUnitTest {
@Test
public void givenUppercaseFileReaderInstance_whenCalledreadFile_thenCorrect() throws Exception {
Path path = Paths.get(getClass().getClassLoader().getResource("files/test.txt").toURI());
BaseFileReader uppercaseFileReader = new UppercaseFileReader(path);
assertThat(uppercaseFileReader.readFile()).isInstanceOf(List.class);
}
}

View File

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

View File

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

View File

@@ -0,0 +1,20 @@
package com.baeldung.innerinterfaces;
import com.baeldung.innerinterfaces.CommaSeparatedCustomers;
import com.baeldung.innerinterfaces.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4.class)
public class InnerInterfaceUnitTest {
@Test
public void whenCustomerListJoined_thenReturnsJoinedNames() {
Customer.List customerList = new CommaSeparatedCustomers();
customerList.Add(new Customer("customer1"));
customerList.Add(new Customer("customer2"));
assertEquals("customer1,customer2", customerList.getCustomerNames());
}
}

View File

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