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 Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Java Program to Implement Treap
Hướng dẫn Java Design Pattern – Decorator
Adding Parameters to HttpClient Requests
Hướng dẫn Java Design Pattern – Flyweight
Immutable Map Implementations in Java
Giới thiệu luồng vào ra (I/O) trong Java
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Removing all Nulls from a List in Java
Java Program to Implement Sorted Circularly Singly Linked List
Java Program to Implement Circular Doubly Linked List
OAuth2.0 and Dynamic Client Registration
Hướng dẫn Java Design Pattern – State
Java Web Services – JAX-WS – SOAP
Java Program to Generate Random Numbers Using Multiply with Carry Method
Java Program to Implement Segment Tree
Lớp TreeMap trong Java
Queue và PriorityQueue trong Java
Guide to Spring 5 WebFlux
Spring REST API with Protocol Buffers
Send an email using the SMTP protocol
Guide to Dynamic Tests in Junit 5
Java Program to do a Depth First Search/Traversal on a graph non-recursively
Quick Guide to the Java StringTokenizer
Introduction to Spring Boot CLI
Java Program to Check for balanced parenthesis by using Stacks
How To Serialize and Deserialize Enums with Jackson
Tạo ứng dụng Java RESTful Client không sử dụng 3rd party libraries
Copy a List to Another List in Java
Feign – Tạo ứng dụng Java RESTful Client
Giới thiệu JDBC Connection Pool
Query Entities by Dates and Times with Spring Data JPA

1 Trackback / Pingback

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

Comments are closed.