Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Array ใน Java เป็น Primitive Type หรือ Object?

Array ใน Java ถือว่าเป็น Object เหตุผลคือ Array สร้างได้ด้วยคีย์เวิร์ด new ซึ่ง new ใช้สร้าง object เสมอ นี่คือเหตุผลที่ array ถูกมองว่าเป็น object

Direct parent class (super class) ของ array ใดๆ คือคลาส Object ทุก array type ใน Java 属于某个 class แสดงว่ามี class แยกสำหรับ int array, float array, double array, ฯลฯ

Array สามารถสร้างแบบไดนามิกและกำหนดให้ตัวแปรได้

ตัวอย่าง

public class Demo {
    public static void main(String[] args) {
        System.out.println("Is the argument an instance of super class Object? ");
        System.out.println(args instanceof Object);
        int[] my_arr = new int[4];
        System.out.println("Is the array my_arr an instance of super class Object? ");
        System.out.println(my_arr instanceof Object);
    }
}

ผลลัพธ์

Is the argument an instance of super class Object? true
Is the array my_arr an instance of super class Object? true

คลาส Demo มี main ใช้ instanceof operator ตรวจสอบว่า args และ array ที่สร้างใหม่ เป็น instance ของ Object หรือไม่ แสดงผล true ทั้งคู่