PDA

View Full Version : constructor query


realtimethrill
07-13-2007, 02:55 PM
Hi
I've a question about this code:

public class Test {

public Test(){}

public static void main(String args[])
{
System.out.println(new Test().i);
}

int i;
}

The Java book I'm consulting says that when you provide a parameterless constructor, you replace the Java-provided default construtor. It also states that the Java-provided default construtor initialises all attributes to a default value -e.g. zero for an integer.

However, if the above code is really replacing the default construtor, then how is int i being set to zero? (When the code is run the integer variable has the value zero)

I suppose in a way this seems a weird question, it's just I'm trying to get a good understanding of the basics.

Any answers welcome!

ess
07-13-2007, 03:48 PM
You are right...it is one confusing topic in Java...and I don't think that the book you are currently reading has provided a good answer to your question.

Basically, every time you declare a class, the Java compiler by default will create an empty class constructor...if your class didn't declare one that is.

As for initializing default values for instance variables...the default class constructor does not play a role in this at all....unless you specifically stated otherwise. In other words, if you declare a class without a constructor...compiled the class...and then uncompiled the class you have just created...you should notice that a default constructor has been added on your behalf by the Java compiler....and it does not initialize any of the instance variables you have declared within your class.

Note: If you want to try this out yourself, there is a very good Java Decompiler called "DJ Java Compiler" which you can download from the following location.
http://members.fortunecity.com/neshkov/dj.html

Therefore, one can assume that once you have declared an instance variable, it will be initialized to its default value at run time by the JVM (Java Virtual Machine)....unless you have assigned a value or used a constructor to assign a default value.

Hope that helps.

Cheers,
Ess

realtimethrill
07-13-2007, 08:45 PM
Cheers Ess, that's great. I tried decompilation as you recommended. The DJ Java Decompiler showed an empty default constructor when you don't add one yourself -just as you said (although the JCavaj Decompiler didn't show any constructor being automatically added).

The Java book I have says:
"Java automatically provides a default constructor... [which] does the 'bare minimum' required to initialise a new object: namely, setting all attributes to their zero-equivalent default values."

So I suppose that's just plain wrong!