Skip to content

Commit e4408fb

Browse files
authored
BAEL-3854 - Pattern Matching for instanceof in Java 14 (eugenp#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
1 parent b5af302 commit e4408fb

2 files changed

Lines changed: 59 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.java14.patternmatchingforinstanceof;
2+
3+
public class PatternMatchingForInstanceOf {
4+
5+
public void performAnimalOperations(Animal animal) {
6+
if (animal instanceof Cat cat) {
7+
cat.meow();
8+
} else if(animal instanceof Dog dog) {
9+
dog.woof();
10+
}
11+
}
12+
13+
abstract class Animal {
14+
}
15+
16+
final class Cat extends Animal {
17+
void meow() {
18+
}
19+
}
20+
21+
final class Dog extends Animal {
22+
void woof() {
23+
}
24+
}
25+
26+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.java14.patternmatchingforinstanceof;
2+
3+
import static org.mockito.Mockito.mock;
4+
import static org.mockito.Mockito.verify;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Cat;
9+
import com.baeldung.java14.patternmatchingforinstanceof.PatternMatchingForInstanceOf.Dog;
10+
11+
class PatternMatchingForInstanceOfUnitTest {
12+
13+
@Test
14+
void givenAnAnimal_whenTypeIsCat_ThenCatGoesMeow() {
15+
Cat animal = mock(Cat.class);
16+
17+
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
18+
instanceOf.performAnimalOperations(animal);
19+
20+
verify(animal).meow();
21+
}
22+
23+
@Test
24+
void givenAnAnimal_whenTypeIsDog_ThenDogGoesWoof() {
25+
Dog animal = mock(Dog.class);
26+
27+
PatternMatchingForInstanceOf instanceOf = new PatternMatchingForInstanceOf();
28+
instanceOf.performAnimalOperations(animal);
29+
30+
verify(animal).woof();
31+
}
32+
33+
}

0 commit comments

Comments
 (0)