Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Amazed that it compiles?

 
AKINLEYE ADEDAMOLA
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is a question from K&B chapter 3 on assignment

class Zippy
{
String []x;
int [] a[] ={{1,2},{1}};
Object c = new long[4];
Object[] d = x;
}

I compiled this and it works.
I was wondering what does new long[4] mean?I thought i ought to have a compile time error.
 
Hrishikesh Maluskar
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It compiles because Object is the base class of all classes and in arrays sub classes can fit into base classes.
 
kaushik vira
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1:- Array is one object so you can Assign it to object type variable

2:- x is instance of Object[] so you can assign x to Object[] for more clarification refer following code.

public class Test
{
int [] a[] ={{1,2},{1}};

Object c = new long[4];
/*Array is one object so you can Assign it to
object type variable*/

String [] x;
Object[] d = x;
/* x is instance of Object[] so you can assign x to Object[] for more clarification refer main()*/

public static void main(String[] args) {
String [] x = new String[1];
Object[] d = x;
if(x instanceof Object[]){
System.out.println(true);
}
}


}
 
AKINLEYE ADEDAMOLA
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am actually confused by the syntax new long[4]? is long[4] supposed not to mean an array with element with index 4
 
Henry Wong
author
Marshal
Pie
Posts: 21207
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by AKINLEYE ADEDAMOLA:
I am actually confused by the syntax new long[4]? is long[4] supposed not to mean an array with element with index 4


"new long[4]" instantiates an array object that hold 4 long values.

Henry
 
Hrishikesh Maluskar
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No its an Array of size 4....and Arrays are ultimately objects,so it will compile
 
AKINLEYE ADEDAMOLA
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh! stupid of me to ask such question? I am used to writing new int[4] that new long[4] didn't occur to me thnxs all for the help
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic