• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

which one is executed first

 
Neha Sawant
Ranch Hand
Posts: 204
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I do not understand when instance variable gets initialized before constructor or after the constructor
here is the following code:
class Test{
int a=6;
Test(){
this(a);
}
Test(int x){
)
public static void main(String args[]){
Test t=new Test();
}
this code give compiler error saying that a has not been initialized.So i thought that constructors are executed before instance variables.
But this code compiles properly
public class Test{
int i;
Test(){
i++;
}
public static void main(String args[]){
Test t=new Test();
S.o.p(t.i);
}
o/p is 1
Can anyone what's happening in these two codes.
Regards
Neha
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Neha
JLS 8.8.5.1 gives the answer

An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs.

HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


[This message has been edited by Marilyn deQueiroz (edited November 24, 2001).]
 
Neha Sawant
Ranch Hand
Posts: 204
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx alot Valentin and Marilyn for your help
Regards
neha
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic