i5h4n
i5h4n

Reputation: 387

Difference between importing class and using it directly in object declaration/initialization

I'd like to know if there is any difference in the following:

import packageX.packageY.classZ;

public void dummyMethod()
{
     classZ dummyObj = new classZ();
}

And

public void dummyMethod()
{
     packageX.packageY.classZ dummyObj = new packageX.packageY.classZ();
}

Any performance/compile-time/run-time differences? Anything at all?

Upvotes: 0

Views: 342

Answers (3)

performance wise or execution wise : no difference at all 1 :

import packageX.packageY.classZ;

void dummyMethod()
{
     classZ dummyObj = new classZ();
}

this is for the mere convenience that you dont have to type the full path everytime

2 :

void dummyMethod(){
     packageX.packageY.classZ dummyObj = new packageX.packageY.classZ();
}

this method will make you type the full path every time you create an instance

the second method is beneficial only in the case

==> when you have to instantiate two objects with the same Class Name from different packages

Upvotes: 1

Osiris
Osiris

Reputation: 4185

The bytecode that's generated is the same - so there's no runtime difference.

import makes the code more readable.

But if there could be conflicts with other classes, you should use fully qualified names.

Upvotes: 4

user2742371
user2742371

Reputation:

There is no difference at all, it doesn't affect speed or performance or anything.

It clearly only affects readability and if you import it you have to type less if you want to use other classes from that namespace.

Even if you import 100 namespaces that are not even being used it does not affect your performance.

Upvotes: 3

Related Questions