can I import,use class from other package? In Eclipse I made 2 packages one is main other is second
main -main (class) second -second (class)
and I wanted the main function of main class to call the function x in second class. how can I do it? I tried:
import second; second.x(); (if both classes are in the same package then it works) second.second.x();
but none of them worked. I'm out of idea now.
The import keyword is used to make the classes of another package accessible to the current package.
You have to provide the full path that you want to import.
import com.my.stuff.main.Main; import com.my.stuff.second.*;
So, in your main class, you'd have:
package com.my.stuff.main import com.my.stuff.second.Second; // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION class Main { public static void main(String[] args) { Second second = new Second(); second.x(); } }
EDIT: adding example in response to Shawn D's comment
There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:
class Main { void function() { int x = my.package.heirarchy.Foo.aStaticMethod(); another.package.heirarchy.Baz b = new another.package.heirarchy.Bax(); } }
Alternatively, this is useful when you want to differentiate between two classes with the same short name:
class Main { void function() { java.util.Date utilDate = ...; java.sql.Date sqlDate = ...; } }
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