nevets1219
nevets1219

Reputation: 7706

How can I avoid a name conflict between a class and a package in Java?

I have two projects, Main and Core. I have a package called com.package.Sample (along with its contents) and a class called Sample in package com.package. If I were to include both in Main, I would run into an error with one being unable to resolve - in my actual case it was the Sample class that could not be resolved. We have ant scripts that builds and that has always worked.

However, carefully examining what was required of each project, I noticed that I could move the package com.package.Sample into Core along with its dependencies that were in Main. The Sample class technically belonged inside of Main so I did not move it. This allowed me to build successfully within Eclipse.

A couple of things I'm wondering about:

Upvotes: 2

Views: 6439

Answers (2)

Skip Head
Skip Head

Reputation: 7760

Package names should be all lowercase, class names should start with a capital. Following this practice makes sure that problems like you describe never occur.

Upvotes: 4

Keith Layne
Keith Layne

Reputation: 3775

To answer your bullets, respectively:

  • I don't know if this is common in large projects, I would assume not. Large projects would probably never become large if the codebase was designed to cause name conflicts (especially in Java, which makes solving problems like this easy).
  • I wouldn't refactor the Sample class if the name is appropriately descriptive. I would however, name my packages (and subpackages) with all lowercase letters. You implied that this is a smallish project, so I'm guessing you have control over naming. I have never seen in my recollection production Java code (commercial or open source) that used any capitals in a package name. Since the convention in Java is to use Pascal case or camel case or whatever you want to call it, if you follow that convention you will never have a class/package name conflict.
  • Of course it will build. Pretty easy fix. Since you are using Eclipse, you should be able to right-click the package in the explorer, choose "refactor", change the name to lowercase, and be pretty much done.

Good luck!

Upvotes: 5

Related Questions