my dog learned polymorphism*
The moose likes Beginning Java and the fly likes instance variables initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "instance variables initialization" Watch "instance variables initialization" New topic
Author

instance variables initialization

anuj thite
Ranch Hand

Joined: Apr 14, 2009
Posts: 49
Hello all ranch members,
i have a doubts regarding instance variables initialization & constructors.
i think these are very simple questions for this forum to answer.
but, i have to get clear my doubts.
please give your opinions on this.

i know that intialising instance variables is a good programming practice.
which is a Standard way for initializing instance variables ??

1st way :-

class MainFrm extends JFrame{
// instance level variables.
private JPanel pn1;
private JPanel pn1;
private JButton btn1;
private JButton btn2;

MainFrm(){
pn1 = null;
pn2 = null;
btn1 = null;
btn2 = null;
----
----
}

---
---
}


2nd way :-

class MainFrm extends JFrame{
// instance level variables.
private JPanel pn1;
private JPanel pn2;
private JButton btn1;
private JButton btn2;

MainFrm(){
----
----
}

---
---
}


3rd way :-

class MainFrm extends JFrame{
// instance level variables.
private JPanel pn1 = null;
private JPanel pn2 = null;
private JButton btn1 = null;
private JButton btn2 = null;

MainFrm(){
----
----
}

---
---
}

i know that defining default constructor explicitly in class definition is a good programming practice.
Is it a good programming practice to add super() as first statement in every constructor definition ??

Waiting for your valuable suggestions.
Thanks in advance.
W. Joe Smith
Ranch Hand

Joined: Feb 10, 2009
Posts: 710
What do you mean add super() to each constructor definition? If you mean a call to the super class constructor it isn't needed as when a class is instatiated the constructors of all its superclasses are called automatically. I believe the term is constructor chaining.

As for how to initialize instance variables, I believe that the first and third ways you posted are better than the second (where it appears you are just letting them get initialized to the default values). By assigning values to the variables yourself it makes your code easier to understand if someone unfamiliar with the language is looking at the code. As far as assigning values in a constructor as opposed to when the variable is declared I personally prefer to assign values when the variable is declared. I think it is nice to just look at one line and be able to say "Hey, this variable awesomeAnswer is an int, and it has a value of 42" as opposed to having to go through the code to find where the assignment is. That is more of a personal preference, and there are times when it does make sense to assign a value later, but I still try to declare a value, even if it is just the default value.


SCJA
When I die, I want people to look at me and say "Yeah, he might have been crazy, but that was one zarkin frood that knew where his towel was."
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Defining a "default" (you mean no-argument) constructor in every class is not a good practice. Never define methods or constructors you don't imagine being used.

Adding "super()" explicitly as the first line of every constructor is likewise not a good practice; it's extra code, for no reason. Don't clutter your code with things you don't need.

Finally, explicitly initializing instance variables to null, and then later setting them to their actual values, is again not a good practice. Initialize them at the point where you have all the information needed to set their initial values, and no earlier.


[Jess in Action][AskingGoodQuestions]
Fred Hamilton
Ranch Hand

Joined: May 13, 2009
Posts: 679
Ernest Friedman-Hill wrote:Defining a "default" (you mean no-argument) constructor in every class is not a good practice. Never define methods or constructors you don't imagine being used.

Adding "super()" explicitly as the first line of every constructor is likewise not a good practice; it's extra code, for no reason. Don't clutter your code with things you don't need.

Finally, explicitly initializing instance variables to null, and then later setting them to their actual values, is again not a good practice. Initialize them at the point where you have all the information needed to set their initial values, and no earlier.


putting aside "proper programming practise" for the moment. It is my understanding that the three methods in the first post are functionally identical.

In other words...

JPanel panel1; and JPanel panel1 = null; are the same, which means that in general declaring an object and assigning a value of null is essentially the same as declaring the object but not instantiating it. Is this a correct interpretation?

edit: by not instantiating, I had meant not using the new operator. I think that means the same thing.

thanks.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi Fred,

The end result will be the same in both cases: the field will contain null. But if you explicitly initialize to null, the compiler will generate code to do that, and that code will be added to the constructor(s) for your class. So there's no discernible effect, but the code is a tiny bit larger and a tiny bit slower.
Troy Travis
Greenhorn

Joined: Jun 15, 2009
Posts: 3
Ernest Friedman-Hill is exactly right. Here's an example and a little explanation:

You can't just willy-nilly do anything in Java because it 'looks good' - aside from formatting of course - and even certain ways of formatting can have an effect on code initialization, such as ordering of class/instance variables and static initialization blocks.

Here is an example where understanding what actually happens when an instance variable is explicitly initialized to null will cause a null-pointer to occur even though it is initialized to a non-null value in an implemented abstract method that is called by the super constructor.

In the following example, the abstract class has one abstract method, doConcreteStuff1, that is intended to be invoked in the constructor of the same class: concrete classes need only implement doConcreteStuff1(). Here we have explicitly set instance variables 'one' and 'two' to null and we initialize them in the implemented doConcreteStuff() method.


What do you think will happen when the code is executed?

When the code is executed the following occurs:

B:One is one
B:Two is two
Exception in thread "main" java.lang.NullPointerException
at base.InstanceVarNull$ConcreteInstanceVarNull.<init>(InstanceVarNull.java:16)
at base.InstanceVarNull.main(InstanceVarNull.java:28)

UGhhh!! A null-pointer!!!

Is that what you expected? After all, we did initialize them to non-null values, but it appears that they were overwritten back to null! What gives?

Let's demonstrate another example. I'll remove the explicit null initialization from the instance variables.


What do you think will happen this time when the new code is executed?

When the code is executed the following occurs:

B:One is one
B:Two is two
A:One is one
A:Two is two

No null-pointer!!!

The question here is, why?

As Ernest Friedman-Hill stated above, by explicitly assigning null to the instance variables (in example 1), the compiler will insert the assignment in the constructor of the concrete class and due to the order of operations, doConcreteStuff1() will indeed get executed BEFORE this assignment. So we will see 2 statements being printed, but after that the concrete class will then initialize and re-assign those variables to null.

However, in the second example, we DO NOT explicitly assign null to the instance variables and the compiler does not assign them as null in the constructor. So when we execute example 2, the only assignment for those variables occurs in the doConcreteStuff1() method, and we have NO null-pointers.

Check out the byte-code of each example if you don't believe me.

Cheers and happy coding!
Troy Travis
Greenhorn

Joined: Jun 15, 2009
Posts: 3
I thought I would add the de-compiled class files to prove my claim:

Here is the generated class file with null explicitly set (example 1, above), more specifically I show the constructor:
Note lines 5 and 10.


, and here is the generated class file with null NOT explicitly set (example 2, above), more specifically I show the constructor:
Note that the null assignment DOES NOT occur in the constructor as it does above, which is the reason why the values do not get overridden and hence no null-pointer!!!


 
jQuery in Action, 2nd edition
 
subject: instance variables initialization