Java - Assigning an array to an object reference -
this question has answer here:
- is array object in java 8 answers
how come can assign array object reference
object x = (object) new int[] { 1, 2, 3 };// no error object y = new int[] { 1, 2, 3 };//no error do java arrays inherit object similar classes?
i expected give me compile time error.
doing this:
system.out.println(x.tostring() + " " + x.getclass().getname() + " " + x.getclass().gettypename()); results in:
[i@15db9742 [i int[]
do java arrays inherit object similar classes?
yes, because arrays instances of classes, other objects. why have hashcode , tostring , getclass, inherit them object.
from jls§10.1:
the supertype relation array types not same superclass relation. direct supertype of
integer[]number[]according §4.10.3, direct superclass ofinteger[]objectaccordingclassobjectinteger[](§10.8). not matter in practice, becauseobjectsupertype of array types.
(my emphasis)
and (perhaps relevant) jls§10.2:
a variable of array type holds reference object.
Comments
Post a Comment