java how to use classes in other package?

后端 未结 3 426
隐瞒了意图╮
隐瞒了意图╮ 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 = ...;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 14:39

    It should be like import package_name.Class_Name --> If you want to import a specific class (or)

    import package_name.* --> To import all classes in a package

    0 讨论(0)
  • 2020-12-01 14:51

    Given your example, you need to add the following import in your main.main class:

    import second.second;
    

    Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

    package main;  //lowercase package names
    public class Main //titlecase class names
    {
        //Main class content
    }
    
    0 讨论(0)
提交回复
热议问题