• Post Reply Bookmark Topic Watch Topic
  • New Topic

polymorphing  RSS feed

 
podonga poron
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class test {}

class test2 extends test{}

class test3 extends test{}

class x {

//If i say this
test[] t = {new test2(), new test3()};
//it compiles perfectly

//But when i say the same as above in a different way
test[] t2 = new test[1];
t2[0]= new test2();
t2[1]= new test3();
//The compiler tells me to create class "t2" WTF !


//And if i declare the same in a public static void ...
public static void main (String[] args){
test[] t3 = new test[3];
t3[0]= new test2();
t3[1]= new test3();
//It works perfectly !!
//why is this ?
}

}
[ June 15, 2008: Message edited by: podonga poron ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't know for sure, since you're only showing a few lines here, but my guess is that in the "error" case, you've got these lines of code

test[] t2 = new test[1];
t2[0]= new test2();
t2[1]= new test3();

outside of any method -- i.e., just inside the class body. The first line is a declaration, and that's OK, but the other two are just plain old executable statements, and that's not OK. You can't put any random lines of Java code at the class level: you have to put them inside a method, like the "main" method you tried in your third case.

OK?
 
podonga poron
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ohh ok !

so in the first line i'm just doing a declaration

and in the second i'm executing (MUST be inside a method)

i got confused since the both statements are the same
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's right -- the first one is a declaration too, so it's OK. That's the form you need to use in a class body.
 
Rakesh Chaudhary
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for such a wonderful explanation sheriff.....
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!