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.

import Java Keyword Example

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

Java 5 introduced a new feature — static import — that can be used to import the static members of the imported package or class. You can use the static members of the imported package or class as if you have defined the static member in the current class.
Example:
import static java.lang.Math.PI;
// class declaration and other members
public double area() {
    return PI * radius * radius;
}
You can also use wildcard character “*” to import all static members of a specified package of class.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments