2013年12月10日星期二

Object in Java and Object [] Why meet type compatibility

Today relive java -based sentence in time to see such a "crazy java notes " in the
" If you want to achieve this infinitely scalable array in java language , you can define an Object [] array type , the array elements are of type Object , so you can point to an array of type Object again " (p101 )
with the code for what it means :

Object[] b = new Object[3];
b[1] = new Object[3];

java in Object and Object [] to meet the type compatibility , it makes me very confused why other reference types , such as String and String [] does not satisfy the type compatibility

String[] s = new String[3];
s[1] = new String[3];

code behind will show Type mismatch: cannot convert from String [] to String
Object and Object [] Why meet type compatibility , hoping to get everyone's interpretation
------ Solution ------------------- -------------------------
this problem is very simple, because object [] which put the object object and its subclasses What does that mean ? That all objects , because all objects are a subclass of Object , so you can put Object Object array inside an array
The String [] String objects can be placed inside the String object and all child classes, but there is no subclass String object , we can only put the String object , but can not put String [] array. Probably it is so
------ Solution ------------------------------------ --------
Object is the parent class of all objects.
Object [] b = new Object [3];
b [1] = new Object [3];
who are new out are objects.
So Object ( parent ) may be new to point out any objects ( subclass ) .


String [] s = new String [3];
s [1] = new String [3];
s is an array of type String , so s [1] is an element of type String .
new String [3] is an array. String type of element (s [1]), can not point to an array .
------ Solution ---------------------------------------- ----
"everything is object"
------ Solution ------------------------- -------------------

arrays and objects , are non-essential to fully relations : All arrays must be the object , but the object is not necessarily the array.
------ For reference only -------------------------------------- -
thank @ ltp2010 and friends upstairs answer , though it was time to raise this issue also understand all the java objects are subclasses of object objects , but for an array type or hold an ambiguous attitude.
Just to check the documents confirming the Object array type is indeed the parent class :
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays , implement the methods of this class
java is also the array as an inherited type , this is a bit different from other languages.
again thank you for your answer , learn !

没有评论:

发表评论