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:

Spring Boot - Tomcat Port Number
Java Program to Implement Singly Linked List
Logging in Spring Boot
Java Program to Implement Quick Sort Using Randomization
Spring Cloud AWS – Messaging Support
Java Program to Perform Sorting Using B-Tree
Java – InputStream to Reader
Merging Streams in Java
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Java Program to Implement Levenshtein Distance Computing Algorithm
Hướng dẫn Java Design Pattern – Composite
Java Program to Implement Efficient O(log n) Fibonacci generator
Wiring in Spring: @Autowired, @Resource and @Inject
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Introduction to Spring Cloud Stream
Control the Session with Spring Security
Java Program to Implement SynchronosQueue API
Lập trình đa luồng với CompletableFuture trong Java 8
Spring 5 and Servlet 4 – The PushBuilder
Control Structures in Java
Java Program to Implement Sorted Doubly Linked List
Using Custom Banners in Spring Boot
Comparing Objects in Java
Java Program to Create a Random Linear Extension for a DAG
Set Interface trong Java
Java Program to Implement Solovay Strassen Primality Test Algorithm
Java Program to Implement Gauss Seidel Method
Java Program to Represent Graph Using Adjacency Matrix
Java Program to Implement Ternary Search Algorithm
Java Program to Generate Randomized Sequence of Given Range of Numbers
Các nguyên lý thiết kế hướng đối tượng – SOLID
Guide to the Synchronized Keyword in Java

1 Trackback / Pingback

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

Comments are closed.