Importing packages in Java

前端 未结 7 756
一向
一向 2020-12-08 14:54

How to import a method from a package into another program? I don\'t know how to import... I write a lil\' code:

package Dan;
public class Vik
{
    public          


        
相关标签:
7条回答
  • 2020-12-08 15:10

    You don't import methods in Java, only types:

    import Dan.Vik;
    class Kab
    {
        public static void main(String args[])
        {
            Vik Sam = new Vik();
            Sam.disp();
        }
    }
    

    The exception is so-called "static imports", which let you import class (static) methods from other types.

    0 讨论(0)
  • 2020-12-08 15:13

    Here is the right way to do imports in Java.

    import Dan.Vik;
    class Kab
    {
    public static void main(String args[])
    {
        Vik Sam = new Vik();
        Sam.disp();
    }
    }
    

    You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.

    0 讨论(0)
  • 2020-12-08 15:13

    In Java you can only import class Names, or static methods/fields.

    To import class use

    import full.package.name.of.SomeClass;
    

    We can also import static methods/fields in Java and this is how to import

    import static full.package.nameOfClass.staticMethod;
    import static full.package.nameOfClass.staticField;
    
    0 讨论(0)
  • 2020-12-08 15:14

    In Java you can only import class Names, or static methods/fields.

    To import class use

    import full.package.name.of.SomeClass;
    

    to import static methods/fields use

    import static full.package.name.of.SomeClass.staticMethod;
    import static full.package.name.of.SomeClass.staticField;
    
    0 讨论(0)
  • 2020-12-08 15:22

    For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"

    0 讨论(0)
  • 2020-12-08 15:24

    You should use

    import Dan.Vik;
    

    This makes the class visible and the its public methods available.

    0 讨论(0)
提交回复
热议问题