Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use two class with the same name in different packages? [duplicate]

How can I access two classes with the same name in different packages?

foo.bar.myClass.class

and

foo.myClass.class

All of this in the same class

@TestRunner(Suite.class)
@SuiteTest({bar.myClass.class, myClass.class})

Thank you.

like image 833
Drahakar Avatar asked Dec 06 '10 15:12

Drahakar


People also ask

Can two classes in different packages have the same name?

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.

Can we create 2 classes with same 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 I import two classes with same name in Java?

One would have the same problem importing those classes in Java code. It's just not possible to import two classes with the same name, because there is no way to tell which one you are referring to when you use the class' name only (e.g. (Application.)). (Application.) (javafx.

Can a class be in multiple packages?

Technically you can have a same class with same content in two different packages but then when you use these 2 classes in another Java class then you would have to be very specific (absolute package name) when using either of the class.


2 Answers

You need to use the fully qualified names of the classes.

 foo.bar.myClass myvar;
 foo.myClass anothervar;
like image 102
Vincent Ramdhanie Avatar answered Oct 14 '22 07:10

Vincent Ramdhanie


you will have to import one and other you will be writting fully qualified path

for example in your code:

import foo.bar.myClass;

.
.
.
myClass ob; // this  will refer to foo.bar.myClass 
foo.myClass ob1 ;//this  will refer to foo.myClass
like image 27
jmj Avatar answered Oct 14 '22 06:10

jmj