Oliver Dixon
Oliver Dixon

Reputation: 7405

Initialize variable as class or constructor?

Which is better or which is right way to do this, can you also give explanation (I didn't know what search term to use on Google).

First way:

Public Class A()
{
    Paint _paint _test;

    public void running()
    {
        _test = new Paint();
       //use paint
    }
}

OR

Public Class B()
{
    Paint _paint _test = new Paint();

    public void running()
    {
        //use paint
    }
}

Thanks

Upvotes: 1

Views: 211

Answers (3)

Will
Will

Reputation: 4713

The answer is 'it depends'. In the case you have illustrated it is probably more elegant to use the second option. However if a value needs to know the value of a constructor parameter or is in any way altered by the construction of the class it should probably be initialised in the constructor. If a member can be initialised at its declaration it should be. This will prevent the need to initialise them to 0 or Null when the class is allocated.

Upvotes: 0

trutheality
trutheality

Reputation: 23455

The first way is better when you might (maybe in the future) possibly want to pass parameters to the member's constructor, e.g:

class Foo{
    private Bar bar;

    public Foo(){
        bar = new Bar();
    }

    public Foo( String s ){
        bar = new Bar( s );
    }
}

The second way is better when you know you will never want to pass parameters to the member's constructor and you have multiple constructors that all need to initialize this member, e.g:

class Foo {
    private Bar bar = new Bar();

    public Foo( String s ){ ... }
    public Foo( int i ){ ... }
    public Foo( double d ){ ... }
    public Foo( String s, int i ){ ... }
}

Upvotes: 4

Vivek Viswanathan
Vivek Viswanathan

Reputation: 1963

It is best to initialize just before it is used. Only initialize variables that are always required/used in the constructor.

Upvotes: -1

Related Questions