简体   繁体   中英

What to do if 2 classes have the same package statement

I'm running into a problem where 2 classes from 2 different packages (owned by the same group) have the same name and package statement

Package 1

package com.placeholder.constants.Constants

public class Constants{}

Package 2

package com.placeholder.constants.Constants

public class Constants{}

If I'm working on Package 1 but want to reference this Constants class in Package 2, is this even possible?

Cannot duplicate class name within same package

where 2 classes from 2 different package

But they are not two different packages. You've used the same package name for both.

want to reference this Constants class in Package 2

Use either:

  • A different package name
  • A different name for your new class

You cannot define two classes with the same name in the same package, for obvious reasons.

The purpose of packages in Java is to create a namespace . Your duplicate class name violates that namespace.

Design problems

package com.placeholder.constants.Constants

That is not a proper package name. You've mixed the class name into the package name. The package should be package com.placeholder.constants .

This cross-naming problem of yours raises the possibility that you have a less than optimal class design. You might want to pause a moment to look at the bigger picture.

And if you have that many constants to name, I wonder if some of those should really be enum types. See tutorial by Oracle . Tip: In Java 16 and later, enums can be defined locally, within an a method — a new alternative to being defined as a nested class or defined as a separate class.

You are facing a name conflict. If possible, try to enter the full name of the package.class_location

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM