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
Yes, it will work.
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.
A class can have only one package declaration but it can have more than one package import statements.
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.
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. } }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With