-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathInstanceOfPatternMatchingExample.java
61 lines (51 loc) · 1.26 KB
/
InstanceOfPatternMatchingExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.demo;
/**
*
* @author hantsy
*/
public class InstanceOfPatternMatchingExample {
public static final void main(String args[]) {
instanceOfBefore14();
instanceOf14();
}
static void instanceOfBefore14() {
System.out.println("Before Java 14:");
Animal animal = new Cat();
if(animal instanceof Cat){
Cat cat = (Cat) animal;
System.out.println("it is a cat:" +cat.name());
}
}
static void instanceOf14() {
System.out.println("In Java 14 or later:");
Animal animal = new Cat();
if(animal instanceof Cat cat){
System.out.println("it is a cat:" +cat.name());
}
}
}
class Animal{
}
class Cat extends Animal{
public String name() {
return "Ketty";
}
@Override
public String toString() {
return "Cat{" + '}';
}
}
class Dog extends Animal{
public String name() {
return "Kael";
}
@Override
public String toString() {
return "Dog{" + '}';
}
}