Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing packages in Java

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

like image 610
Daniel Victor Avatar asked Sep 03 '12 13:09

Daniel Victor


People also ask

How do you import an entire package in Java?

Importing an Entire Package To import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character. Now you can refer to any class or interface in the graphics package by its simple name. Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();

What are packages in Java with example?

Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. For example there can be two classes with name Employee in two packages, college.


2 Answers

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.

like image 136
Gustav Barkefors Avatar answered Sep 28 '22 06:09

Gustav Barkefors


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; 
like image 23
Pshemo Avatar answered Sep 28 '22 06:09

Pshemo