Master Core Java Concepts!
Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!
Subscribe Now on YouTube3 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:
import packagename.*;— Imports all classes and interfaces of that package (excluding sub-packages).import packagename.ClassName;— Imports only a specific class from the package.- Fully Qualified Name — Uses
packagename.ClassNamedirectly in your code without needing animportstatement.
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.
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.
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.