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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值