Home Field vs field and new object
Reply: 1

Field vs field and new object

Gregory
1#
Gregory Published in 2018-01-09 13:48:47Z

I was wondering what is the diffrence between these two situations:

class Cell
{
    Messages msg;

    public void getMessage()
    {
        msg.getMessage();
    }
}

and:

class Cell
{
    Messages msg = new Messages();

    public void getMessage()
    {
        msg.getMessage();
    }
}

I know that in the first example I declared only field, and in the second I declared field, object and assigned object to the field. But in the both situations I can use .getMessage() method in Cell class, so what is diffrence and what should I use?

Adrien Brunelat
2#
Adrien Brunelat Reply to 2018-01-09 14:37:16Z

In the second case, the Messages member will be instantiated upon Cell instantiation. That means that msg = new Messages() will be called when you write new Cell() somewhere in your code.

In the first case, if you instantiate Cell (with new Cell() for instance) and call the getMessage() method without setting anything to msg first, you'll get a NullPointerException since the value of an object member is null by default. This will not be the case in the code you wrote in your second example.

Which solution you should use depends on what you want to do with your code. Both are acceptable and I fear this point is mainly opinion based. You can find more details on a similar question here: Best practice for initializing an ArrayList field in Java.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.334149 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO