Skip to content

Packages in Java Programming

  • an essential concept for organizing your code.

🔹 What Are Packages in Java?

A package in Java is a namespace that organizes a set of related classes and interfaces.

Think of it like a folder in your computer where you group similar files together. Similarly, in Java, you group related classes and interfaces into a package to keep your code modular, readable, and maintainable.


🔹 Types of Packages

1. Built-in Packages

Java provides many pre-defined packages that we use in our programs, such as:

  • java.lang – Fundamental classes (like String, Math, Integer)
  • java.util – Utility classes (like ArrayList, Date, HashMap)
  • java.io – Input/output classes (like File, BufferedReader)
  • java.sql – For database access
  • javax.swing – GUI development

2. User-defined Packages

You can also create your own packages to better organize your project.


🔹 Syntax to Create and Use Packages

🔸 1. Creating a Package

package mypackage;

public class MyClass {
    public void show() {
        System.out.println("Hello from MyClass!");
    }
}
  • The package statement must be the first line in the Java file (except comments).
  • The class MyClass is now part of the mypackage.

🔸 2. Using a Package (Importing)

To use the class from the package, you need to import it:

import mypackage.MyClass;

public class Test {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.show();
    }
}

OR import everything from the package:

import mypackage.*;

🔹 Why Use Packages?

Purpose Description
Modularity Organizes code into modules
Reusability Code can be reused across projects
Namespace control Prevents name conflicts between classes
Access protection Classes and members can be made accessible only within packages using access modifiers

🔹 Access Modifiers & Packages

  • public: Accessible from any package
  • protected: Accessible within the package and in subclasses
  • default (no modifier): Accessible only within the same package
  • private: Not accessible outside the class

🔹 Real-World Analogy

Imagine a library with different sections (packages):

  • Fiction → library.fiction.*
  • Science → library.science.*
  • History → library.history.*

Each section contains books (classes) related to that topic. That’s how packages work.


🔹 Sample Questions

🟡 Theoretical

  1. What is the purpose of packages in Java?
  2. List some commonly used built-in packages in Java.
  3. Explain the difference between import mypackage.* and import mypackage.MyClass.

🟢 Coding

Q: Write a program with a package animals, containing a class Dog with a method bark(). Then use it in another class.

Answer **File 1: Dog.java**
package animals;

public class Dog {
    public void bark() {
        System.out.println("Woof! Woof!");
    }
}
**File 2: TestDog.java**
import animals.Dog;

public class TestDog {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.bark();
    }
}

Absolutely! Let's explore more definitions and ways to describe Packages in Java to strengthen your understanding.


Definitions of Packages in Java (Different Perspectives)

📘 Basic Definition

A package in Java is a group of related classes, interfaces, and sub-packages. It helps organize code logically and prevents class name conflicts.


📘 Textbook-style Definition

In Java, a package is a mechanism to encapsulate a group of related types (classes, interfaces, enumerations, and annotations) together. Packages help in avoiding naming conflicts, controlling access, and organizing classes for easy maintenance and reusability.


📘 Technical Definition

A Java package is a namespace that provides a structured hierarchy for managing class files. It acts like a directory structure for organizing Java files, similar to folders in a file system.


📘 Object-Oriented Perspective

Packages promote modular programming in Java. Each package contains logically related types, which allows developers to create clean interfaces and encapsulate implementation details.


📘 Developer's Perspective

Think of a package as a tool to manage your project. As your project grows, packages help keep related files together and reduce complexity, just like dividing a book into chapters.


📘 Comparison-based Definition

Just like files are grouped into folders in an operating system, Java classes are grouped into packages. This organization helps developers manage and maintain large software projects.


📝 Key Points to Remember

Feature Description
Grouping Packages group related classes and interfaces
Namespace Prevents name clashes between classes
Access control Enables controlled visibility using access modifiers
Reusability Encourages reuse of standard or user-defined packages
Maintenance Makes the project more structured and maintainable

Access Protection in Java, also known as Access Modifiers.


🔐 What is Access Protection in Java?

Access Protection in Java controls which parts of your program can access a class, method, or variable. Java uses access modifiers to enforce these rules.

This is a key part of encapsulation, one of the core principles of Object-Oriented Programming (OOP). It allows you to hide internal details of a class and expose only what is necessary.


🔑 Types of Access Modifiers in Java

Java provides four types of access protection levels:

Modifier Class Package Subclass (in other pkg) World (anywhere)
private
default (no keyword)
protected
public

🔸 1. private

  • Access only within the same class
  • Used to hide data from other classes
class Example {
    private int number = 10;

    private void display() {
        System.out.println("Private method");
    }
}

🚫 Can't access number or display() from outside the Example class.


🔸 2. Default (No modifier)

  • Accessible within the same package only
  • Also called package-private
class Example {
    int number = 20; // default access

    void show() {
        System.out.println("Default method");
    }
}

✅ Can be accessed by other classes in the same package 🚫 Cannot be accessed from another package


🔸 3. protected

  • Accessible within the same package, and also by subclasses in other packages
class Animal {
    protected void sound() {
        System.out.println("Animal sound");
    }
}

✅ Useful when you want to allow inheritance + limited access


🔸 4. public

  • Accessible from anywhere (any class, any package)
public class Test {
    public void show() {
        System.out.println("Public method");
    }
}

✅ No restriction at all


🧠 Summary Table

Modifier Visibility Scope
private Inside the same class only
(default) Inside the same package
protected Same package + subclasses in other pkgs
public Accessible from everywhere

🎓 Real-life Analogy

Imagine a house:

  • private: Only the owner can enter the bedroom
  • default: Family members in the same house can access the kitchen
  • protected: Family members + close relatives with keys can access the living room
  • public: The garden is open to everyone

📝 Common Exam Questions

  1. Define access modifiers in Java.
  2. Differentiate between private, default, protected, and public.
  3. What is the purpose of using access protection in object-oriented programming?

Importing Packages in Java Programming

📦 What Does It Mean to "Import a Package" in Java?

Importing a package in Java means telling the compiler that you want to use classes or interfaces defined in another package.

Think of it like saying:

“Hey Java, I want to use this ready-made class from a package instead of writing it myself.”

It allows you to reuse existing code from built-in or user-defined packages.


🔹 Why Import Packages?

  • To reuse pre-written code (like Scanner, ArrayList, etc.)
  • To avoid writing fully qualified class names
  • To organize code cleanly and modularly
  • To access user-defined classes from other files

🔹 Syntax of Import Statement

The import statement is written after the package declaration (if any), and before the class declaration.

import package_name.class_name;

OR

import package_name.*;

🔸 1. Importing a Specific Class

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
    }
}

You are telling Java: “I want to use the Scanner class from java.util package.”


🔸 2. Importing All Classes in a Package

import java.util.*;

This imports all classes and interfaces from the java.util package, like ArrayList, Scanner, HashMap, etc.

🚫 Note: It does not import sub-packages.


🔸 3. No Need to Import java.lang

Some packages are automatically imported, like java.lang:

String name = "Java";  // String is in java.lang

So you don’t need:

import java.lang.String;  // ❌ Not required

🔸 4. Importing User-Defined Packages

Imagine you have a package called mypack:

// File: MyClass.java
package mypack;

public class MyClass {
    public void greet() {
        System.out.println("Hello from MyClass!");
    }
}

Then in another file:

// File: Main.java
import mypack.MyClass;

public class Main {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.greet();
    }
}

🎯 Rules for Importing Packages

  • You can’t import private classes from another package.
  • If two classes have the same name, use fully qualified name:
java.util.Date date1 = new java.util.Date();
java.sql.Date date2 = new java.sql.Date(System.currentTimeMillis());

🧠 Summary

Syntax Meaning
import java.util.*; Imports all classes from java.util
import java.util.Date; Imports only the Date class
No import needed for java.lang It’s imported automatically

📝 Common Exam Questions

  1. What is the purpose of the import statement in Java?
  2. What is the difference between import java.util.Scanner; and import java.util.*;?
  3. Why don't we need to import classes from the java.lang package?

Interfaces in Java

🔷 What is an Interface in Java?

An interface in Java is a blueprint of a class. It is a reference type, like a class, but it can only contain:

  • Abstract methods (method declarations without a body)
  • Constants (public static final variables)
  • Default and static methods (from Java 8 onwards)

Interfaces define what a class must do, but not how it does it.


🔸 Example:

interface Animal {
    void makeSound();  // abstract method
}

Any class that wants to become an Animal must implement the makeSound() method.

class Dog implements Animal {
    public void makeSound() {
        System.out.println("Woof!");
    }
}

🔷 Key Points About Interfaces

Feature Description
Cannot be instantiated You can't create an object of an interface directly
No constructors Interfaces do not have constructors
Abstract by default All methods are abstract and public (before Java 8)
Variables All variables are public static final (constants)
Multiple implementation A class can implement multiple interfaces (unlike classes, which only extend one class)

🔷 Syntax

Creating an Interface:

interface Vehicle {
    void start();
    void stop();
}

Implementing an Interface:

class Car implements Vehicle {
    public void start() {
        System.out.println("Car started");
    }
    public void stop() {
        System.out.println("Car stopped");
    }
}

🔷 Java 8+ Features

From Java 8, interfaces can contain:

1. Default methods

interface MyInterface {
    default void greet() {
        System.out.println("Hello!");
    }
}

2. Static methods

interface MyInterface {
    static void show() {
        System.out.println("Static method in interface");
    }
}

🔷 Real-world Analogy

Think of an interface as a remote control:

  • It has buttons (methods) but doesn’t define how the device works inside.
  • A TV and a fan may use the same interface but implement it differently.

🔷 Interface vs Abstract Class

Feature Interface Abstract Class
Multiple inheritance ✅ Yes ❌ No
Constructors ❌ No ✅ Yes
Variables public static final only Any type
Methods Abstract, default, static Can be abstract or concrete
Inheritance Implement using implements Extend using extends

🔷 Why Use Interfaces?

  • To achieve abstraction
  • To support multiple inheritance
  • To standardize functionality across different classes
  • To define APIs and contracts in software development

📝 Common Exam Questions

  1. What is an interface in Java?
  2. How is an interface different from an abstract class?
  3. Can an interface have variables? If yes, what type?
  4. What are default and static methods in interfaces (Java 8+)?

✅ Summary

  • Interface = contract or blueprint
  • Contains method signatures (no body)
  • Implemented by classes using implements
  • Supports multiple inheritance
  • Promotes abstraction and flexibility