Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java how to use classes in other package?

Tags:

java

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.

like image 798
ace Avatar asked Aug 13 '10 20:08

ace


People also ask

Which key word is used to use classes from other packages?

The import keyword is used to make the classes of another package accessible to the current package.


1 Answers

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 = ...;     } } 
like image 133
atk Avatar answered Sep 19 '22 03:09

atk