A package is a way to group related classes and interfaces together in Java. It helps organize code and avoid name conflicts. Packages also provide access control and make it easier to manage large projects.
A package is defined at the beginning of a Java file using the package keyword. To use a class from another package, the import statement is used.
package animals;
public class Dog {
public void bark() {
System.out.println("Bark");
}
}
import animals.Dog;
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.bark();
}
}
In this example, the
Dogclass is part of theanimalspackage. TheMainclass imports it using theimportstatement before using it.