Article View: borland.public.jbuilder.java.language
Article #15017Illogical constructor behaviour?
From: Tom.Eugelink
Date: Mon, 12 Jul 1999 00:00
Date: Mon, 12 Jul 1999 00:00
65 lines
2524 bytes
2524 bytes
I found (using JBuilder3) a IMHO illogical behaviour of Java. This is
not a trivial problem, so bear with me if you are interested. My
question: can someone tell me if I'm seeing things wrong?
The core problem is that Java does not DECLARE (assign values to)
instance variables until the first line of code in the constructor is
about to be executed. It does allocate the variables on class
creation, but not declare them.
This can result in the situation where methods are executed before the
instance variables have been declared.
Example:
There are two classes, one inherits the other, and both have a private
instance variable being declared in the definition line and each class
also has a method with the same name. Not considering the logic of the
program, the structur below shows the set-up:
public class fireman extends person
{
private JTextField x = new JTextField("x");
public fireman( String something )
{
super(something);
x.setText(something);
}
public display()
{
System.err.println(x.getText());
}
}
public class person
{
private JTextField y = new JTextField("x");
public person( String something )
{
y.setText(something);
display();
}
public display()
{
System.err.println(y.getText());
}
}
If the execution trace is considered, the following relevant steps
occur in sequence when an instance of fireman is created:
1. classes and the variables are allocated
2. program execution enters the constructor of fireman and immediatly
steps to person
3. program execution enters the constructor of person and just before
the display is executed, all variables are declared.
4. display is called
5. program execution enters display at FIREMAN level!
6. the getText call in the display in fireman crashes because x has
not been assign an instance of JTextField yet.
It seems to me there is no reason why the declares shouldn't be
executed when the constructor is entered instead of just before the
first line in the constructor...
Technical Details
Message-ID:
<3789a7ea.1163072@forums.inprise.com>Path:
arc1-ca.pugleaf.net!unknown!not-for-mailShow Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit X-Google-Thread: f74b3,c150801d0979e255,start X-Google-Attributes: gidf74b3,public From: Tom.Eugelink@OVSoftware.com Subject: Illogical constructor behaviour? Date: 1999/07/12 Message-ID: <3789a7ea.1163072@forums.inprise.com> X-Deja-AN: 500037034 Organization: Another Netscape Collabra Server User Newsgroups: borland.public.jbuilder.java.language