Packages
In Java, a package is a namespace used to organize classes and interfaces. Packages help avoid name conflicts and make it easier to locate and use classes and interfaces.
Types of Packages:
Built-in Packages: These are provided by Java. Examples include:
java.util
java.io
java.math
User-defined Packages: These are created by developers to organize their own classes.
Example of Creating and Using Packages:
Creating a package:
package com.example.animals;
class Dog {
void bark() {
System.out.println("Barking...");
}
}
Using a class from a package:
import com.example.animals.Dog;
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.bark(); // Output: Barking...
}
}