If an array of Object is an Object, why is an array of String not a String

后端 未结 6 1400
心在旅途
心在旅途 2021-02-15 12:06

Object class is super class to every class in Java. So every class should inherent the properties or behavior of Object class.

Then we can declare array of objects as sh

6条回答
  •  Happy的楠姐
    2021-02-15 12:55

    Somewhat confusingly, an Object[] is an Object. (For one thing this is how Java can implement zero-length arrays, and allow arrays to be function return values).

    So assigning an Object[] instance to a reference of type Object type makes sense.

    But assigning a String[] instance to a reference of type String does not make sense. (But note that String[] is also an Object.)

    So

    1. Object c = new Object[] {1,2,"22" }; Makes sense
    2. String s = new String[]{"s","s"}; Doesn't make sense
    3. Object s = new String[]{"s","s"}; Makes sense

提交回复
热议问题