thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2281

JAVA: why Object [] obj = {new Object[1],new Object[2]} and not other classes?

Hi I have seen that Object [] obj = {new Object[1],new Object[2]} is allowed and I am not sure why it is. If I use other classes instead of Object it's generating errors (like Integer, or ArrayList, or even my classes like Grandpa, Dad and Me)?

Upvotes: 2

Views: 5859

Answers (4)

Suresh Atta
Suresh Atta

Reputation: 121998

Your signature satisfied the condition, an array of any Objects.

Object [] obj = {new Object[1],new Object[2]}

Because new Object[1] is an Array and That is also an Object, Since every Class extends Object

Upvotes: 2

Amith
Amith

Reputation: 1434

Object [] obj = {Can have any type of Object because every class by default extends Object Class}

X [] obj = { Array of objects of X Class}

Example:

String[] obj = { Array of String Objects}

Granpa[] gandobj = { Array of Granpa Objects}

Upvotes: 0

Rahul
Rahul

Reputation: 45070

Since even an Object[] is an object that's why its not throwing any error. But in reality, what you're actually doing is assigning an array to an Object.

Object[][] obj = {new Object[1],new Object[2]}; // proper way
Object[] obj = {new Object[1],new Object[2]}; // this works because Object[] is treated as an Object

That won't work in the case of String or anything else as each element in a String array has to be a String and not a String array.

String[][] obj = {new String[1],new String[2]}; // proper way as its a 2d array where each element in itself is a 1d array.
String[] obj = {new String[1],new String[2]}; // this won't because each element in String array must be a String
String[] obj = {new String("1"),new String("2")}; // this will work as each element is a string

Upvotes: 4

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

obj is just an Object array here. Also Array is a Object too So what is the issue. Object is a base class for any class in Java.

Object [] obj = {Element Should be Objects}

So Array is an Object too.

Upvotes: 0

Related Questions