Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
initialization in and out of constructor Posted by allelopath on 8 Jul 2005 at 9:00 AM
A question about initialization of native types
I would like to do this:

public class Foo
{
int x = null;

// constructor
public Foo
{
x = 1;
}

}

but assigning null to x does not work since null is not an int
This works:

public class Foo
{
int x = 1;

// constructor
public Foo
{
}

}

but I don't like that x is not initialized in the constructor.

Stepping thru the debugger at the point of the constructor, it does jump up to the int x = 1; line, as if it were actually in the constructor.

Is this the best one can do?

This doesn't apply to actual classes because they can be initialized to null.
Report
Re: initialization in and out of constructor Posted by Vilanye on 8 Jul 2005 at 6:39 PM
This message was edited by Vilanye at 2005-7-8 18:40:22

public class Foo
{
int x;//don't forget visability modifier, usually private or protected

// constructor
public Foo
{
x=1;
}

}

Either way works just as well, but explicitly initializing values in the constructor seems cleaner to me. You don't even have to have a constructor or even define values. If you do not have either, the variable is set to 0, false or null depending on the type.

Also, note that this works with variables with the final modifier, which is very unlike C or C++.

public class Foo
{
private final int x;

// constructor
public Foo
{
x=1;
}

}





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.