Win a copy of Machine Learning for Business: Using Amazon SageMaker and JupyterE this week in the Jython/Python forum
or Object Design Style Guide in the Object-Oriented programming forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
  • Knute Snortum
Sheriffs:
  • Liutauras Vilda
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Joe Ess
  • salvin francis
  • fred rosenberger

Constructor initialization sequence

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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
  • 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
 
I once met a man from Nantucket. He had a tiny ad
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!