C

Core Java tutorial for beginners

Clean • Professional

Java - Packages and Access Modifiers with Examples

4 minute

Packages & Access Modifiers in Java


In Java, packages and access modifiers are essential concepts that help you organize and secure your code.

  • Packages group related classes and interfaces together for better project structure.
  • Access modifiers control who can access those classes, methods, and variables.

Together, they make your Java program modular, reusable, and secure.


What is a Package in Java?

A package is a namespace that organizes related classes and interfaces.

Think of it as a folder in your computer that helps keep your files (classes) organized.

com.myapp.utils

Here:

  • com → main domain package
  • myapp → project name
  • utils → sub-package (utility classes)

Benefits of Using Packages

  • Avoids name conflicts between classes.
  • Makes code modular and easier to maintain.
  • Enables access control using access modifiers.
  • Supports reusability by importing only what’s needed.

Types of Packages

Java provides two types of packages:

learn code with durgesh images

TypeDescriptionExample
Built-in (Predefined)Already available in Java APIjava.util, java.io, java.lang
User-definedCreated by developerscom.myapp.utils, school.student

Example – Built-in Package

import java.util.Scanner; // importing predefined class

public class InputExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = sc.nextLine();
        System.out.println("Hello, " + name);
    }
}

Here, java.util is a built-in package, and Scanner is a class inside that package.


Example – User-defined Package

// File: mypack/Message.java
package mypack;

public class Message {
    public void display() {
        System.out.println("Welcome to Java Packages!");
    }
}
// File: Main.java
import mypack.Message;

public class Main {
    public static void main(String[] args) {
        Message m = new Message();
        m.display();
    }
}

Output:

Welcome to Java Packages!

Access Modifiers in Java

Access modifiers define how accessible a class, method, or variable is from other classes or packages.

There are four main access levels in Java:

learn code with durgesh images

1. private Access Modifier

  • The most restrictive access level.
  • Members declared private are accessible only within the same class.
  • Not visible in subclasses or anywhere else.
public class PrivateExample {
    private int data = 42;

    private void display() {
        System.out.println("Private data: " + data);
    }

    public static void main(String[] args) {
        PrivateExample obj = new PrivateExample();
        obj.display(); // Accessible here
    }
}
class TestPrivate {
    public static void main(String[] args) {
        // PrivateExample obj = new PrivateExample();
        // obj.display();  Error - display() is private
    }
}

2. Default Access Modifier (Package-Private)

  • When no modifier is specified, it becomes default.
  • Accessible only within the same package.
  • Not visible outside the package — even to subclasses.
package mypack;

class Example {
    void show() {
        System.out.println("Default access modifier example");
    }
}

public class TestDefault {
    public static void main(String[] args) {
        Example e = new Example();
        e.show(); // Works - same package
    }
}
package anotherpack;

import mypack.Example;

public class TestOutside {
    public static void main(String[] args) {
        // Example e = new Example();  Error - not accessible
    }
}

3. protected Access Modifier

  • The protected modifier gives access within the same package and to subclasses (even in different packages).
  • Useful for inheritance.

Example:

package mypack;

public class Parent {
    protected void display() {
        System.out.println("Protected method in Parent class");
    }
}
package anotherpack;

import mypack.Parent;

class Child extends Parent {
    void show() {
        display(); // Accessible because Child is a subclass
    }

    public static void main(String[] args) {
        Child c = new Child();
        c.show();
    }
}

Output:

Protected method in Parent class


4. public Access Modifier

  • Most open access level.
  • Members declared public can be accessed from anywhere — inside or outside the package.
  • Commonly used for API methods or shared classes.

Example:

package mypack;

public class A {
    public void show() {
        System.out.println("Public method in class A");
    }
}
package anotherpack;

import mypack.A;

public class TestPublic {
    public static void main(String[] args) {
        A obj = new A();
        obj.show(); // Accessible everywhere
    }
}

Output:

Public method in class A

Diagram:

+-----------------+           +-----------------+
|   Package A     |           |   Package B     |
|-----------------|           |-----------------|
| Class1 (public) |           | Class3 (public) |
| Class2 (private)|           | Class4 (protected)|
+-----------------+           +-----------------+

Access Levels:
- public: Accessible from anywhere
- protected: Accessible in same package + subclasses
- default: Accessible in same package only
- private: Accessible within class only

Example – Combining Packages and Access Modifiers

// File: company/Employee.java
package company;

public class Employee {
    protected int id;
    public String name;

    public void display() {
        System.out.println("ID: " + id + ", Name: " + name);
    }
}
// File: office/Main.java
package office;
import company.Employee;

public class Main extends Employee {
    public static void main(String[] args) {
        Main emp = new Main();
        emp.id = 101; // accessible (protected)
        emp.name = "John";
        emp.display();
    }
}

Output:

ID: 101, Name: John

Points to Remember

  • Packages organize related classes.
  • Access modifiers control visibility and security.
  • Import statement is used to access classes from other packages.
  • Protected gives access to subclasses across packages.
  • Private members cannot be accessed outside their class.

Real-world Example Addition

Scenario: Employee Management System

// File: company/Employee.java
package company;

public class Employee {
    protected int id;        // accessible in subclasses
    public String name;      // accessible anywhere

    public void display() {
        System.out.println("ID: " + id + ", Name: " + name);
    }
}

// File: office/Main.java
package office;
import company.Employee;

public class Main extends Employee {
    public static void main(String[] args) {
        Main emp = new Main();
        emp.id = 101;          // protected → accessible because Main extends Employee
        emp.name = "John";     // public → accessible anywhere
        emp.display();
    }
}

Output :

ID: 101, Name: John

 

Article 0 of 0