Rajath
Rajath

Reputation: 215

What is the difference in creating objects in these two ways

what is the difference between creating an object like like

OverFlow a = new OverFlow();

OverFlow a;

Upvotes: 0

Views: 112

Answers (8)

Nitram76
Nitram76

Reputation: 421

OverFlow a;

equals

OverFlow a = null;

Upvotes: 1

Phillip Schmidt
Phillip Schmidt

Reputation: 8818

Basically,

OverFlow a;

tells the compiler, "There is eventually going to be a variable of type overflow, so get ready for it."

OverFlow a = new Overflow();

actually allocates the memory needed to store the variable and invokes the constructor for it

Upvotes: 0

NPE
NPE

Reputation: 500963

The

OverFlow a

bit has the same meaning in both cases: it creates a variable called a that stores a reference to an instance of class OverFlow (or a subclass).

In the first case, a new object is created and the reference is initialized to point to that object.

In the second case, the reference is not initialized and remains null.

Upvotes: 1

mprivat
mprivat

Reputation: 21912

OverFlow a; does not create an object (i.e. an instance you can use). It only defines the variable a with the type OverFlow but it will be assigned to null. If you try to use it, you will therefore get a NullPointerException. Depending on your compiler, it will also most likely give you an 'uninitialized' variable warning.

OverFlow a = new OverFlow(); does the same thing, except it makes an actual object (non-null) that is ready to be used.

Upvotes: 0

Sebastian A.
Sebastian A.

Reputation: 33

When you create an object without defining it as a new Object, it will not be initialized (the constructor doesn't get called, either.). You should only use the second version to create objects within a try-catch-block.

Upvotes: 0

kevin628
kevin628

Reputation: 3526

In the first one, "a" has a value of a the newly constructed OverFlow object.

In the second one, it is null.

Upvotes: 0

Sven Hager
Sven Hager

Reputation: 3204

new OverFlow();

really creates an instance of class OverFlow, while

OverFlow a;

is just a declaration.

Upvotes: 0

Dmitry Ovsyanko
Dmitry Ovsyanko

Reputation: 1416

In second case, no object is created. The a variable remains uninitialized.

Upvotes: 2

Related Questions