What are access specifiers and access modifiers in Java?

203    Asked by CharlesParr in Java , Asked on Jan 2, 2024

There is a scenario where I am designing a system where I have multiple classes that can interact with each other. Explain to me how can I use access specifiers and modifiers for controlling the visibility and accessibility of a wide range of class members, methods, and even fields in my system for ensuring encapsulation, security, and maintainability. 

Answered by Chris EVANS

 In the context of Java programming language the access specifiers and access modifiers in Java are keywords which is used in defining the accessibility, and visibility of classes, methods, and even variables in your particular program.

There are four access specifiers in Java programming language which are given below:-

Public

The members when declared as “public” then it would be accessible from any class.

Public class MyClass {
    Public int publicVariable;
    Public void publicMethod() {
        // Method logic here
    }
}

Private

The members when declared as “public” then it would be accessible within the same class.

Public class MyClass {
    Private int privateVariable;
    Private void privateMethod() {
        // Method logic here
    }
}

Protected

Tge members when declared as “protected” then it would be accessible within the same subclass.

Public class MyClass {
    Protected int protectedVariable;
    Protected void protectedMethod() {
        // Method logic here
    }
}

Default

If there is no accessible then there are “default” access specifiers in Java programming language.

Class MyClass {
    Int defaultVariable;
    Void defaultMethod() {
        // Method logic here
    }
}


Your Answer

Interviews

Parent Categories