Showing posts with label Package Access. Show all posts
Showing posts with label Package Access. Show all posts

Monday, 7 September 2015

Java Tutorial : Java package access

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

3 Ways to Access a Package in Java

In Java, when you want to access a class or interface from outside its package, there are three different ways you can do it:

  1. import packagename.*; — Imports all classes and interfaces of that package (excluding sub-packages).
  2. import packagename.ClassName; — Imports only a specific class from the package.
  3. Fully Qualified Name — Uses packagename.ClassName directly in your code without needing an import statement.

1. Using import packagename.*;

Adding import mypack.*; makes every class and interface inside mypack accessible. However, keep in mind that sub-packages are not imported automatically—you must import them separately if needed.

package util;
import mypack.*;

public class B {
  public static void main(String[] args) {
    A obj = new A();
    obj.message();
  }
}

2. Using import packagename.ClassName;

If you only need a single class, importing it directly (for example, import mypack.A;) keeps your imports clean and explicit.

3. Using a Fully Qualified Name

When two different packages contain classes with the exact same name—such as java.util.Date and java.sql.Date—you can use the fully qualified name (packagename.ClassName) to avoid any ambiguity without writing an import statement.

package util;

public class A {
  public static void main(String[] args) {
    mypack.A obj = new mypack.A();
    obj.message();
  }
}

Important Rule: Order of Statements

✔️ When writing a Java file, always place the package statement first, followed by import statements, and then the class declaration.


Watch More Java Tutorials:

Tutorials