This commit is contained in:
myluckagain 2018-02-19 05:30:31 +05:00 committed by Predrag Maric
parent 6385ba4fb0
commit fe97d98c30
6 changed files with 127 additions and 0 deletions

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,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,58 @@
package com.baeldung.casting;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
public class CastingTest {
@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);
}
}