From the course: Pattern Matching for Switch in Java 21
What is pattern matching? - Java Tutorial
From the course: Pattern Matching for Switch in Java 21
What is pattern matching?
- [Instructor] What is pattern matching? Well, pattern matching is about testing an object against a particular structure and extracting data from that object if there's a match. In this video, I'm going to teach you how the instanceof operator is used for this. Then let's gradually move on to pattern matching with switch. For example, if there's a person object and two subtypes of it called student and employee, you can check if the person is a student and if so, extract their marks. If not, that is, if the person is an employee, extract their salary. This can be implemented using the instanceof operator, then it would look like this. First, here's the Person interface. There's the Student class that implements the Person interface. The Student class has a property named marks, a constructor and a getter method for marks. Here's the Employee class that also implements Person. The Employee class has a property named salary, a constructor and a getter method for salary. In the Main class, in the getPersonData method, you use the instanceof operator to check if the object, obj, is an employee. If so, you have to cast it to an employee object and then retrieve the salary from it. If not, if obj is a student, you cast it to a student object and then retrieve marks from it. In the Main method, if you create a person who's an employee and pass it to the getPersonData method, then it'll print the employee's salary. This is because the object is an instanceof an employee. Likewise, if you create another person, a student object, and pass it to the getPersonData method, it'll print the student's marks, and that's because the object is an instanceof a student. Let's run and see. So it prints the employee's salary, followed by the student's marks. There's pattern matching happening here, but in this traditional way, you have to perform manual casting of objects. But later on, a concept known as pattern matching was introduced to be used with the instanceof operator. This was actually the motivation for pattern matching for switch in Java 21. Let's have a look at it in the next video.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.