Importing packages in Java

2019-01-22 06:50发布

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 void disp()
    {
        System.out.println("Heyya!");
    }
}

and then, saved it in a folder named "Dan" and I compiled it. The .class file is generated. Then, I wrote this code below:

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

and I saved it outside the folder "Dan" and it says : "cannot find symbol"

I saved the first code in C:\Dan\Vik.java and the second in C:\Kab.java

7条回答
仙女界的扛把子
2楼-- · 2019-01-22 07:33

You should use

import Dan.Vik;

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

查看更多
仙女界的扛把子
3楼-- · 2019-01-22 07:36

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;
查看更多
放荡不羁爱自由
4楼-- · 2019-01-22 07:41

Take out the method name from in your import statement. e.g.

import Dan.Vik.disp;

becomes:

import Dan.Vik;
查看更多
淡お忘
5楼-- · 2019-01-22 07:48

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;"

查看更多
相关推荐>>
6楼-- · 2019-01-22 07:49

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.

查看更多
倾城 Initia
7楼-- · 2019-01-22 07:50

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;
查看更多
登录 后发表回答