How is an array declared/initialized by default in java?

时间:2015-10-06 09:05:39

标签: java arrays serialization access-modifiers

I wanted to ask that what is the default access specifiers/modifiers for an array in java? For example if I write

int arr[];

What will it be by default? Is it public abstract final or public by default?

I am asking this question because I am unable to understand comment made by Tom Ball.

I found why default serialVersionUIDs for arrays were different. That calculation includes the class's modifiers, and it turns out all arrays are "public abstract final", not "public" (a new "gotcha" Java interview question :-). Changing that in the runtime, and now all arrays have the same UIDs, even different object classes.

Here is the link https://groups.google.com/d/msg/j2objc-discuss/1zCZYvxBGhY/ZpIRKPLFBgAJ

Can Someone explain?

2 个答案:

答案 0 :(得分:2)

您链接的帖子指的是(动态创建的,合成的)类对象的访问修饰符,它表示数组:int[].class

类的修饰符与字段的修饰符之间没有关系。

这样想:类java.lang.Stringpublic,但你可以自由地创建一个String类型的private字段。

答案 1 :(得分:2)

当你写一个像

这样的声明时
int arr[];

您要声明变量。您正在声明这个变量正好具有那些访问修饰符。如果未在类变量上指定任何修饰符,则默认情况下它将是package-private。请注意,变量永远不会abstract

您不理解引用文本的原因是,您将变量类型的修饰符与变量的修饰符混淆。

将数组放在一边,如果声明类似Foo bar的变量,则类Foo具有独立于变量bar的修饰符的修饰符。

现在,这同样适用于数组类型。在Java中,数组是对象,因此具有类类型。在运行时,您可以像对任何其他对象一样在数组上调用getClass(),并且您将获得表示合成类的Class对象。您还可以通过类文字访问数组类:

Class<?> clazz=int[].class; // int[]
int mod=clazz.getModifiers();
if(Modifier.isPublic(mod)) System.out.print("public ");
if(Modifier.isAbstract(mod)) System.out.print("abstract ");
if(Modifier.isFinal(mod)) System.out.print("final ");
System.out.print(clazz);
System.out.print(" implements");
for(Class<?> cl:clazz.getInterfaces())
  System.out.print(" "+cl.getName());
System.out.println();

会打印

public abstract final class [I implements java.lang.Cloneable java.io.Serializable

显示表示数组类型int[]的类具有特殊名称[I以及修饰符abstractfinal,这是普通类不可能的组合。< / p>

请注意,如果数组类是原始值数组或其元素类型为public,则数组类为public。如上所述,这并不能阻止您声明此类型的非public变量。