Reputation: 1020
I got this question as an assignment:
Packages/Naming
We have created lot of packages and defined classes and interfaces in them. We have also discussed the point we have to remember while naming them. In this assignment we will see how important naming is.
Please change the package names in your previous assignment such that two packages have same name and analyze the result/errors that will be thrown.
My Doubt:
I am unable to think of a way(scenario) to demonstrate what has been asked. Since Java imports are absolute, the situation described in question seem impossible to produce (IMO).
Please help me to demonstrate this thing.
Thanks in advance :)
Upvotes: 3
Views: 7318
Reputation: 58770
That will depend heavily on the code that you're running.
The only way to cause a package name conflict is to put two separate jars on your classpath that both contain classes in the same package. If none of the class names conflict, then there is no conflict. If some class names do conflict, then the JVM will try to load them from the jar that comes earlier in the classpath. Errors will occur when some classes are only in the later jar, and the classes in the later jar use classes whose names are also used in the earlier jar. The nature of the error depends on the type of use.
(I should clarify that this answer applies to Pure Java, and has no relation to how any particular IDE or build system might generate jars for a project.)
Upvotes: 3
Reputation: 25074
Yes, if you change the package name you'll need to change the imports as well. If you happen to use Eclipse, there's an easy way to do this. In the Package Explorer view, right click on the package and do Refactor->Rename. It will rename the package and update all relevant imports in other classes.
Here's how it could work:
JavaProjectA
src
com.some.package
ClassA
JavaProjectB
src
com.another.package
ClassA
Fine so far. Each class is unique because of its package structure. However, its possible to create this:
JavaProjectA
src
com.some.package
ClassA
JavaProjectB
src
com.some.package
ClassA
Only one of those ClassA classes will get exported in a jar and used at runtime.
Upvotes: 4