• 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
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Constructor initialization sequence

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear all,
I'm confused by the following code. Why the call to "this(y)" makes compilation error? If I replace "this(y)" with "y=2", it runs fine.
--
class SuperType {
int y=2;
SuperType (int x) {
System.out.println("in constructor SuperType(int)");
}
SuperType () {
this(y);
System.out.println("in constructor SuperType()");
}
public static void main(String [] args) {
SuperType t = new SuperType ();
}
}
 
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
y is an instance variable, it is initialized after 'this(y)' statement, which creates an error. Change it to static variable will solve the problem.

[This message has been edited by huiying li (edited October 14, 2001).]
 
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this() and super() call in a constructor is called "explicit
constructor invokation". Those calls can not refer to any
instance variables or members of the current object.
As Huiying indicated, they can only be referenced after
returning from those calls.
JLS 8.8.5.1 says:


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.


[This message has been edited by Nain Hwu (edited October 14, 2001).]
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hcleung,
Please read the JavaRanch Name Policy and re-register using a name that complies with the rules.
Thanks for your cooperation.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic