Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same class name in different packages

Tags:

java

package

Can same class exist in multiple packages? In other words, can I have Foo.java class in com.test.package1 and com.test.package2?

Update

Now I copied class from package 1 and placed in to package 2 and now I am creating an instance of that class, I want this instance to point to class present in package 1 but currently it points to package1 path, how can i modify it?

Oh so I cannot do something like:

Foo = new Foo() // pointing to Foo class in package 1 Foo = new Foo() // pointing to Foo class in package 2 
like image 701
Rachel Avatar asked Oct 29 '10 20:10

Rachel


People also ask

Can package name be same as class name?

Yes, it will work.

Can we have multiple Java classes with the same name in the same package?

A Java file contains only one public class with a particular name. If you create another class with same name it will be a duplicate class. Still if you try to create such class then the compiler will generate a compile time error.

Can a class be in multiple packages?

A class can have only one package declaration but it can have more than one package import statements.

Can Java class have same name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur. But this is not recommended as per coding standards in Java. Normally the constructor name and class name always the same in Java.


2 Answers

Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two import statements. You'll have to fully qualify one of the class names if you really need to reference both of them.


Example: Suppose you have

pkg1/SomeClass.java

package pkg1; public class SomeClass { } 

pkg2/SomeClass.java

package pkg2; public class SomeClass { } 

and Main.java

import pkg1.SomeClass;   // This will... import pkg2.SomeClass;   // ...fail  public class Main {     public static void main(String args[]) {         new SomeClass();     } } 

If you try to compile, you'll get:

$ javac Main.java Main.java:2: pkg1.SomeClass is already defined in a single-type import import pkg2.SomeClass; ^ 1 error 

This however does compile:

import pkg1.SomeClass;  public class Main {      public static void main(String args[]) {         new SomeClass();         new pkg2.SomeClass();   // <-- not imported.     } } 
like image 184
aioobe Avatar answered Sep 21 '22 01:09

aioobe


Sure can but you'll need to distinguish which one you want when calling them in other packages if both are included within a source file.

Response to Comment:

com.test.package1.Foo myFoo = new com.test.package1.Foo(); com.test.package2.Foo myOtherFoo = new com.test.package2.Foo(); 
like image 35
wheaties Avatar answered Sep 21 '22 01:09

wheaties