class Test
{
public static void main(String[] args)
{ String[] str={"IT","is","a","test"};
Object objs=str; // How this work
Object[] objts=str; // how this work
}
}
You have to consider two things here.
First, a reference of type Object that is > objs
and a reference of type Objcet[] that is > objts
Arrays are genuine objects in
Java.
And Object is the mother of all classes i.e at the top of the hierarchy.
Here is the key:
A reference of an array can always be cast to a referece of type Object.
And a referece to array of type objects can be cast to a reference of type Object[]
In the example above: String[] str={"IT","is","a","test"};
This is essentially a two dimentional array: a String[] (i.e. String array) of Strings.
Here, str is reference to an array, so you can cast to type Object, i.e.
cast it to > Object objs=str;
And since, str is also a reference to an array of Objects (i.e. String within this String[], "IT, "is", "a", "test")
It can be cast to that of Object[] (Object array).
Thus >Object[] objts=str;
But if your code had the array as, say: int[] intArray = {1,2,3,4,5}
then you could only do the first cast, but not the second cast.
Why?
Esam.