26

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

Jav_Rock
  • 22,059
  • 20
  • 123
  • 164
Daniel Victor
  • 649
  • 2
  • 7
  • 11

7 Answers7

19

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.

Gustav Barkefors
  • 5,016
  • 26
  • 30
12

In Java you can only import non-primitive types, or static methods/fields.

To import types use import full.package.name.of.TypeName;

//example
import java.util.List; //to import List interface

to import static methods/fields use

import static full.package.name.of.TypeName.staticMethod;
import static full.package.name.of.TypeName.staticField;

//example
import static java.lang.Math.max; //to import max method(s)
import static java.lang.Math.PI; //to import PI field
Pshemo
  • 122,468
  • 25
  • 185
  • 269
8

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

import Dan.Vik.disp;

becomes:

import Dan.Vik;
Chris B
  • 925
  • 4
  • 14
2

You should use

import Dan.Vik;

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

MvG
  • 57,380
  • 22
  • 148
  • 276
ncmathsadist
  • 4,684
  • 3
  • 29
  • 45
2

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.

Apurv
  • 4,458
  • 2
  • 21
  • 31
1

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

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

CyberPlayerOne
  • 3,078
  • 5
  • 30
  • 51