Java Interview Questions - Access specifier

1. What are the access specifiers present in java?

There are four types of access specifier present in java I,e public, protected, default, private.

  1. What is scope of each access specifier? Public – A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java . Protected – Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members’ class. Default – without any access modifier (i.e, public private or protected). It means that it is visible to all within a particular package. Private – Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.

3. Give the details about public keyword in java?

The public keyword is used in the declaration of a class, method, or field; public classes, methods, and fields can be accessed by the members of any class.

4. Why Private access specifier cannot access outside the class?

Private members are the member of same class and encapsulate within the same class object.

5. What are access specifiers and access modifiers present in java , What is the difference b/w them?

By using access specifier we define that who one can access our class/method and variable (or whatever with that we use access specifier ). basically java access specifier are four types -

  1. public,
  2. private,
  3. protected, and
  4. default

But access modifiers are properties of a class/method/variable while access modifiers are five types:

  1. final
  2. static
  3. Synchronized
  4. abstract
  5. transient

6. What are Transient and Volatile Modifiers?

Volatile is a access modifier that informs to the compiler that the variable with this modifier can be changed unexpectedly by other elements of the program. The transient access modifier is used at the time of object serialization in order not to serialize the instance variable value.

7. What modifiers may be used with top-level class?

Public or default modifiers used with top-level class.