Java Modifiers


In Java, modifiers are special keywords that define how classes, methods, and variables can be accessed and used within a program. They help control the visibility, behavior, and restrictions of program elements.

Java modifiers are mainly divided into two categories:

  1. Access Modifiers — control the visibility or accessibility of classes, methods, and variables.

  2. Non-Access Modifiers — define additional features like static, final, abstract, synchronized, etc.

Understanding modifiers is essential for designing secure and efficient object-oriented programs.

Types of Modifiers in Java

Category Examples Purpose
Access Modifiers public, private, protected, default Control visibility between classes and packages
Non-Access Modifiers static, final, abstract, synchronized, transient, volatile Add specific behavior or restrictions

Let’s explore both types in detail.

1. Access Modifiers

Access modifiers define the scope of a class, method, or variable. They decide who can access what part of your code.

a. public

The public modifier makes classes, methods, or variables accessible from anywhere in the program.

Example:

public class Student {
    public String name;

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

public class Main {
    public static void main(String[] args) {
        Student s = new Student();
        s.name = "Anjali";
        s.display();
    }
}

Output:

Name: Anjali

Here, everything marked public can be accessed from any class in any package.

b. private

The private modifier makes a member accessible only within the same class. It is used to protect data and follow encapsulation principles.

Example:

class Account {
    private double balance;

    private void showBalance() {
        System.out.println("Balance: " + balance);
    }

    void deposit(double amount) {
        balance += amount;
        showBalance(); // private method can be called within same class
    }
}

public class Main {
    public static void main(String[] args) {
        Account acc = new Account();
        acc.deposit(1000);
        // acc.showBalance(); // Error: showBalance() has private access
    }
}

Output:

Balance: 1000.0

Private members cannot be accessed directly from outside the class.

c. protected

The protected modifier allows access within the same package and by subclasses even if they are in different packages.

Example:

class Animal {
    protected void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void bark() {
        sound(); // Accessible because of protected
        System.out.println("Dog barks");
    }
}

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

Output:

Animal makes a sound  
Dog barks

Protected members are visible to subclasses, promoting inheritance.

d. Default (No Modifier)

If you don’t specify any modifier, it becomes package-private, meaning it is accessible only within the same package.

Example:

class Student {
    String name;  // default access

    void show() {
        System.out.println("Name: " + name);
    }
}

Default members are not accessible outside their package.

Access Modifier Summary Table

Modifier Same Class Same Package Subclass Other Package
public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

2. Non-Access Modifiers

Non-access modifiers define how classes, methods, or variables behave, not who can access them.

a. static

The static keyword means the member belongs to the class, not an instance. You can access it without creating an object.

Example:

class MathUtils {
    static int square(int n) {
        return n * n;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(MathUtils.square(5)); // No object needed
    }
}

Output:

25

Static members are shared across all objects of the class.

b. final

The final keyword is used to declare constants, prevent inheritance, or prevent method overriding.

1. final variable – value cannot be changed once assigned.

final int MAX = 100;

2. final method – cannot be overridden by subclasses.

class A {
    final void show() {
        System.out.println("Hello");
    }
}

3. final class – cannot be inherited.

final class Vehicle { }

c. abstract

Used to define abstract classes or methods that must be implemented by subclasses.

Example:

abstract class Shape {
    abstract void draw();
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing Circle");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.draw();
    }
}

Output:

Drawing Circle

You cannot create an object of an abstract class.

d. synchronized

Used in multithreading to ensure that only one thread executes a method at a time.

Example:

class Printer {
    synchronized void printDocument(String msg) {
        System.out.println(msg);
    }
}

This ensures safe thread execution.

e. transient

Used for variables that should not be serialized (saved) when writing an object to a file.

transient int password;

f. volatile

Ensures that a variable’s value is always read from the main memory, not from a thread’s cache — useful in multithreaded environments.

volatile boolean running = true;

Non-Access Modifier Summary Table

Modifier Meaning Usage
static Belongs to class, not instance Methods, variables
final Cannot be changed or overridden Class, method, variable
abstract Incomplete implementation Class, method
synchronized Thread-safe execution Methods
transient Excluded from serialization Variables
volatile Always read latest value Variables

Summary of the Tutorial

In this tutorial, you learned about Java Modifiers — special keywords that control access and behavior.

  • Access Modifiers (public, private, protected, and default) control visibility.

  • Non-Access Modifiers (static, final, abstract, synchronized, transient, volatile) define special properties or restrictions.

Modifiers help make Java programs more secure, organized, and efficient by managing how classes and members interact with each other.


Practice Questions

1. Create a class Car with a private variable speed. Add public methods setSpeed(int s) and getSpeed() to modify and access the speed. Demonstrate encapsulation in main().

2. Write a program with a public class Student that has public methods to input and display student details. Create another class Main to call these methods.

3. Create a protected method showMessage() in a class Parent. Inherit it in class Child and call it inside main() to show how protected access works.

4. Write a program with a default access class PackageDemo that prints a message. Try to access it from another package and observe the behavior.

5. Create a static method multiply(int a, int b) in a class MathUtils that returns the product of two numbers. Call this method without creating an object.

6. Define a final variable PI = 3.1416 and use it in a method to calculate the area of a circle. Try to reassign it and note the compiler’s response.

7. Write a program with a final method displayInfo() in class A and try to override it in class B. Observe what happens.

8. Create an abstract class Shape with an abstract method calculateArea(). Inherit it in Rectangle and Circle classes and implement the method in both.

9. Write a multithreading program with a synchronized method printNumbers() that prints numbers from 1 to 5. Start two threads and ensure they don’t print simultaneously.

10. Create a class User with two fields: String username and transient String password. Serialize the object and show that the password is not stored in the file after serialization.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top