Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

initialization in and out of constructor

allelopathallelopath Posts: 26Member
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.

Comments

  • VilanyeVilanye Posts: 684Member
    [b][red]This message was edited by Vilanye at 2005-7-8 18:40:22[/red][/b][hr]
    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;
    }

    }


Sign In or Register to comment.