BAEL-3854 - Pattern Matching for instanceof in Java 14 (#8799)

* BAEL-3491 - Check for null before calling parse in the
Double.parseDouble

* BAEL-3491 - Check for null before calling parse in the
Double.parseDouble

- Return to indentation with spaces.

* BAEL-3854 - Pattern Matching for instanceof in Java 14

* BAEL-3854 - Pattern Matching for instanceof in Java 14 - add unit test
This commit is contained in:
Jonathan Cook 2020-03-03 07:15:28 +01:00 committed by GitHub
parent e646343e20
commit 84a0cb5498
2 changed files with 59 additions and 0 deletions

View File

@ -0,0 +1,26 @@
package com.baeldung.java14.patternmatchingforinstanceof;
public class PatternMatchingForInstanceOf {
public void performAnimalOperations(Animal animal) {
if (animal instanceof Cat cat) {
cat.meow();
} else if(animal instanceof Dog dog) {
dog.woof();
}
}
abstract class Animal {
}
final class Cat extends Animal {
void meow() {
}
}
final class Dog extends Animal {
void woof() {
}
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.java14.patternmatchingforinstanceof;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Cat;
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Dog;
class PatternMatchingForInstanceOfUnitTest {
@Test
void givenAnAnimal_whenTypeIsCat_ThenCatGoesMeow() {
Cat animal = mock(Cat.class);
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
instanceOf.performAnimalOperations(animal);
verify(animal).meow();
}
@Test
void givenAnAnimal_whenTypeIsDog_ThenDogGoesWoof() {
Dog animal = mock(Dog.class);
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
instanceOf.performAnimalOperations(animal);
verify(animal).woof();
}
}