java how to use classes in other package?

后端 未结 3 443
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 14:14

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 w

3条回答
  •  抹茶落季
    2020-12-01 14:36

    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 = ...;
        }
    }
    

提交回复
热议问题