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:

  1. Avoid name conflicts between classes.

  2. Organize classes logically (like utility classes, database classes, etc.).

  3. Control access with access modifiers (public, protected, default, private).

  4. Makes it easier to maintain and reuse code.


📁 Types of Packages:

TypeExample
Built-injava.lang, java.util, etc.
User-definedYour 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:


package mypack; // package declaration public class MyClass { public void showMessage() { System.out.println("Hello from mypack.MyClass"); } }

2. Compiling the Package

In the terminal:


javac -d . MyClass.java

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:


import mypack.MyClass; // import the class from package public class Test { public static void main(String[] args) { MyClass obj = new MyClass(); obj.showMessage(); } }

4. Compiling and Running:


javac Test.java java Test

✅ Output:


Hello from mypack.MyClass

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Java Compiler and Java Virtual Machine