Toán tử instanceof trong java

Toán tử instanceof trong java được sử dụng để kiểm tra một đối tượng có phải là thể hiện của một kiểu dữ liệu cụ thể không.

instanceof trong java được gọi là toán tử so sánh kiểu vì nó so sánh thể hiện với kiểu dữ liệu. Nó trả về giá trị boolean là true hoặc false.

Nếu dùng toán tử instanceof với bất kỳ biến nào mà có giá trị null, giá trị trả về sẽ là false.

1. Kiểm tra kiểu Wrapper

Kiểu Wrapper bao gồm các kiểu dữ liệu: String, Integer, Double, …

Ví dụ

public class InstanceofExample {
    public static void main(String[] args) {
        String str = "Welcome to maixuanviet.com";
        System.out.println(str instanceof String); // true
         
        Integer num = 10;
        System.out.println(num instanceof Integer); // true
    }
}

2. Một đối tượng có kiểu của lớp con thì cũng có kiểu của lớp cha

Ví dụ, nếu Dog kế thừa Animal thì đối tượng của Dog có thể tham chiếu đến cả hai lớp Dog và Animal.

class Animal {
     
}
public class Dog extends Animal {
    public static void main(String[] args) {
        Dog dog = new Dog();
        System.out.println(dog instanceof Dog); // true
        System.out.println(dog instanceof Animal); // true
    }
}

3. instanceof với biến có giá trị null

Ví dụ:

public class InstanceofExample {
    public static void main(String[] args) {
        Dog dog = null;
        System.out.println(dog instanceof Dog); // false
    }
}

4. Downcasting với toán tử instanceof

Khi kiểu của lớp con tham chiếu tới đối tượng của lớp cha được gọi là downcasting. Các bạn xem thêm ở bài viết Cơ chế Upcasting và Downcasting trong java để hiểu rõ hơn về downcasting.

Nếu thực hiện tham chiếu trực tiếp thì trình biên dịch sẽ báo lỗi biên dịch. Nếu thực hiện bằng việc ép kiểu thì lỗi ngoại lệ ClassCastException được ném ra lúc runtime. Nhưng nếu sử dụng toán tử instanceof thì downcasting được.

Tham chiếu trực tiếp: gặp lỗi biên dịch.

Dog dog = new Animal(); // Compilation error

Sử dụng ép kiểu dữ liệu: không lỗi lúc biên dịch, nhưng gặp lỗi ClassCastException lúc runtime.

public class Dog extends Animal {
    static void method(Object obj) {
        Dog dog = (Dog) obj;// downcasting
        System.out.println("downcasting is ok");
    }
 
    public static void main(String[] args) {
        Animal dog = new Dog();
        Dog.method(dog); // downcasting is ok
         
        Object obj = new Rectangle();
        Dog.method(obj); // Error runtime: ClassCastException
    }
}

Kết quả:

downcasting is ok
Exception in thread "main" java.lang.ClassCastException: com.maixuanviet.oop.Rectangle cannot be cast to com.maixuanviet.oop.Dog

Ví dụ downcasting với instanceof như sau:

public class Dog extends Animal {
    static void method(Object obj) {
        if (obj instanceof Dog) {
            Dog dog = (Dog) obj; // downcasting
            System.out.println("ok downcasting performed");
        } else {
            System.out.println("obj is not instance of Dog");
        }
    }
 
    public static void main(String[] args) {
        Animal dog = new Dog();
        Dog.method(dog);
         
        Object obj = new Rectangle();
        Dog.method(obj);
    }
}

Kết quả:

ok downcasting performed
obj is not instance of Dog

Related posts:

Java Program to Perform Insertion in a BST
“Stream has already been operated upon or closed” Exception in Java
Getting a File’s Mime Type in Java
Apache Commons Collections SetUtils
Spring Boot - Building RESTful Web Services
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Spring Boot - Cloud Configuration Server
Check If a File or Directory Exists in Java
Lấy ngày giờ hiện tại trong Java
Java Program to Implement Hash Tables with Linear Probing
Java Program to Optimize Wire Length in Electrical Circuit
SOAP Web service: Authentication trong JAX-WS
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
How to Get a Name of a Method Being Executed?
Immutable Map Implementations in Java
Java Program to Find the Nearest Neighbor Using K-D Tree Search
Removing all duplicates from a List in Java
Java Program to Implement Shunting Yard Algorithm
Apache Commons Collections OrderedMap
HashSet trong Java hoạt động như thế nào?
Java Program to Solve Travelling Salesman Problem for Unweighted Graph
Hướng dẫn Java Design Pattern – Proxy
Hướng dẫn Java Design Pattern – Bridge
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Guide to CountDownLatch in Java
Introduction to Java Serialization
Java Program to Implement the String Search Algorithm for Short Text Sizes
Spring’s RequestBody and ResponseBody Annotations
Giới thiệu JDBC Connection Pool
Spring Boot with Multiple SQL Import Files
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Java Program to Check whether Directed Graph is Connected using DFS

1 Trackback / Pingback

  1. Cơ chế Upcasting và Downcasting trong java – Blog của VietMX

Comments are closed.