天天看點

import_Keyword

import Java Keyword with Examples

The import keyword makes one class or all classes in a package visible in the current Java source file. Imported classes can be referenced without the use of fully−qualified class names.

In simple words, if a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other.

Here, a class named Teacher is added to the com.javaguides.teacher package that already contains Course. The Teacher can then refer to the Course class without using the com.javaguides.teacher.

package com.javaguides.teacher;

import com.javaguides.course.Course;

public class Teacher {
 
 List<Course> courses = new ArrayList<>();
 public void addCourse(Course course) {
  courses.add(course);
 }
}      

The Teacher class used one of the following techniques for referring to a class in a different package.

The fully qualified name of the class can be used. For example:

import com.javaguides.course.Course;

The package can be imported using the import keyword and the wildcard (*). For example:
import com.javaguides.course.*;
Few more examples are:
import java.io.File;
import java.net.*;      

Note that many Java programmers use only specific import statements (no ‘*’) to avoid ambiguity when multiple packages contain classes of the same name.

Java static import

import static java.lang.Math.PI;
// class declaration and other members
public double area() {
    return PI * radius * radius;
}