• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

which one is executed first

 
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 9109
12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


[This message has been edited by Marilyn deQueiroz (edited November 24, 2001).]
 
Neha Sawant
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanx alot Valentin and Marilyn for your help
Regards
neha
 
I've been selected to go to the moon! All thanks to this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic