tags:

views:

52

answers:

4

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

Update

Now I copied class from package1 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 1 package Foo class
Foo = new Foo() // pointing to 2 package Foo class
+3  A: 

yes and thats the whole point of packages. After seeing update to your question I strongly think you need to spend sometime learning programing basics

Pangea
Hmm.. I think your last comment was uncalled for...
aioobe
i didn't mean it in a negative way. however I wanted to strongly suggest him/her for his/her own good
Pangea
A: 

yes, you can do that.

shsteimer
+3  A: 

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();
wheaties
so here is my next question, how can i do that because currently i am calling them but instead of referring to package2 class, code is referring to package 1 class.
Rachel
@Rachel there you go.
wheaties
+3  A: 

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;
import pkg2.SomeClass;

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();
    }
}
aioobe
@aioobe: can you looking into my updated question ?
Rachel
@aioobe: This is exactly the issue am facing and what is the work around for it ?
Rachel
@aioobe - you are quick
Rachel
Updated the answer. You'll have to fully qualify one of the class-identifiers. :-)
aioobe