数组也是对象

  • Post author:
  • Post category:其他


Object类是一个特殊的类,是所有类的父类,如果一个类没有用extends明确指出继承于某个类,那么它默认继承Object类。所有对象都实现这个类的方法。数组的父类也是Object,java中的数组是对象。java中数组的创建使用了关键字new,数据基本类型只有 boolean, byte, short, char, int, long, float, double 8种。

// Java program to display class of 
// int array type
public class Test
{
    public static void main(String[] args)
    {
        int[] x = new int[3];
        System.out.println(x.getClass().getName());
    }
}

输出结果为

[I 

“[”表示这是一个数组,而且是一维的,“I”表示数组元素是int类型的。

通过这个方法还可以打印其他类型的数组名来:

Array type             Corresponding class Name
int[]                     [I
int[][]                   [[I
double[]                  [D
double[][]                [[D
short[]                   [S
byte[]                    [B
boolean[]                 [Z