Packages in Java
📦 What Are Packages in Java?
A package in Java is a namespace that organizes a set of related classes and interfaces. Think of it as a folder in your file system that groups related files together.
🎯 Purpose of Packages:
-
Avoid name conflicts between classes.
-
Organize classes logically (like utility classes, database classes, etc.).
-
Control access with access modifiers (
public,protected,default,private). -
Makes it easier to maintain and reuse code.
📁 Types of Packages:
| Type | Example |
|---|---|
| Built-in | java.lang, java.util, etc. |
| User-defined | Your own custom packages |
✅ Example: Creating and Using a Package
1. Creating a Package
Create a file named MyClass.java in a folder called mypack.
📄 MyClass.java:
2. Compiling the Package
In the terminal:
This creates a mypack directory and places the .class file inside.
3. Using the Package
Create another file in the same folder or a different folder:
📄 Test.java:
4. Compiling and Running:
✅ Output:
Comments
Post a Comment