Access Modifiers in Java: Complete Guide

In this article, we will have a detailed exploration of Access Modifiers in Java. So, let’s get started.

What are Access Modifiers in Java ?

Access modifiers in Java are keywords that determine the visibility and accessibility of classes, methods, variables, and constructors in a Java program. They control the extent to which different parts of your code can be accessed by other classes or packages.

Types of Access Modifiers in Java

There are four types of access modifiers :

  1. Default
  2. Private
  3. Protected
  4. Public

Default

When no access modifier is specified for a class , method or data member – It is said to be having the default access modifier by default.

The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.

Private

The private access modifier is specified using the keyword private. The data members, class or methods having private access modifier is accessible only within the class in which they are declared.

Protected

The protected access modifier is specified using the keyword protected. The data members, class or methods having protected access modifier are accessible within the same package and also in the subclasses in different packages.

Protected = default + subclasses in different packages.

Public

The public access modifier is specified using the keyword public. The data members, class or methods having public access modifier are accessible everywhere.

Arranged in Increasing Access Scope

Access Modifiers in Java
Screen Shot 2020-03-07 at 8.45.35 PM

Interface Access Modifiers

In Java, interface access modifiers determine the accessibility of interfaces when they are accessed from other classes or packages. There are two main access modifiers that can be used with interfaces:

Public: An interface declared as public can be accessed from any other class or package. This means that classes from different packages can implement the public interface.

public interface PublicInterface {
    // Interface methods here
}

Default: If no access modifier is specified, which is also known as the default, the interface is only accessible within the same package. This means that only classes within the same package can implement the interface.

interface DefaultInterface {
    // Interface methods here
}

Interfaces in Java must be declared with either public or default access modifiers. The private and protected access modifiers are not applicable to interface declarations.

Access Modifiers and Inheritance

When a subclass inherits from a superclass, the access level of the inherited members (fields and methods) can affect how they can be accessed from the subclass. Here are some rules:

  • A subclass cannot inherit private members from its superclass because private members are not visible outside the class where they are defined.
  • A subclass can inherit default, protected, and public members from its superclass.
  • An inherited default member is accessible within the same package as the subclass, but not from outside the package.
  • An inherited protected member is accessible within the same package as the subclass and by the subclass itself (even if the subclass is in a different package).
  • An inherited public member is accessible from anywhere.

Code Example: Access Modifiers and Inheritance

Let’s consider a practical code example to illustrate how access modifiers and inheritance work together:

// Superclass with various access-modifier members
class Vehicle {
    public String publicField = "Public Field";
    protected String protectedField = "Protected Field";
    String defaultField = "Default Field";
    private String privateField = "Private Field";

    public void publicMethod() {
        System.out.println("Public Method");
    }

    protected void protectedMethod() {
        System.out.println("Protected Method");
    }

    void defaultMethod() {
        System.out.println("Default Method");
    }

    private void privateMethod() {
        System.out.println("Private Method");
    }
}

// Subclass inheriting from Vehicle
class Car extends Vehicle {
    void accessInheritedMembers() {
        System.out.println(publicField);     // Accessible
        System.out.println(protectedField);  // Accessible
        System.out.println(defaultField);    // Accessible
        // System.out.println(privateField); // Not accessible (private)
        
        publicMethod();     // Accessible
        protectedMethod();  // Accessible
        defaultMethod();    // Accessible
        // privateMethod();  // Not accessible (private)
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.accessInheritedMembers();
    }
}

Access Modifiers With Method Overriding

When a subclass overrides a method from its superclass, the access level of the overridden method can affect its visibility and accessibility from various contexts:

  • The access level of an overridden method in the subclass cannot be more restrictive than the access level of the method in the superclass. In other words, a subclass cannot reduce the visibility of an inherited method.
  • The access level of an overridden method can be the same as or less restrictive than the access level of the method in the superclass.

Code Example: Access Modifiers and Method Overriding

Let’s consider a practical code example to illustrate how access modifiers and method overriding work together:

class Shape {
    protected void draw() {
        System.out.println("Drawing a shape");
    }
}

class Circle extends Shape {
    // Overriding the draw method
    @Override
    protected void draw() {
        System.out.println("Drawing a circle");
    }
}

public class Main {
    public static void main(String[] args) {
        Shape shape = new Circle();
        shape.draw(); // Calls the overridden method in Circle class
    }
}

Conclusion: Access Modifiers in Java

In this article, we delved into the world of access modifiers in Java, uncovering how they control the visibility and accessibility of various class members. We explored four fundamental access modifiers – default, private, protected, and public – each with distinct scopes and limitations.

We learned that default access allows members to be accessible only within the same package, while private members are confined to their declaring class. Protected members, on the other hand, extend access to subclasses even if they are in different packages, and public members are open for access from anywhere.

We also ventured into the realm of interface access modifiers, highlighting the significance of public and default access for interfaces and the impact on implementation across packages.

Furthermore, we examined the interplay between access modifiers and inheritance, discovering that subclasses inherit default, protected, and public members from their superclasses. We grasped the importance of maintaining or expanding access levels while overriding methods to ensure that the intended behavior is retained.

Lastly, through practical code examples, we saw access modifiers and method overriding in action, solidifying our understanding of how these concepts work together to shape Java’s object-oriented paradigm.

By mastering access modifiers in Java, you’re equipped to strike a balance between encapsulation and accessibility, ensuring your Java codebase is well-structured, maintainable, and adheres to the principles of object-oriented programming.

Leave a Reply

Your email address will not be published. Required fields are marked *