Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is the difference between public, protected, package-private and private in Java?

In Java, are there clear rules on when to use each of access modifiers, namely the default (package private), public, protected and private, while making class and interface and dealing with inheritance?
by

2 Answers

seetharamrao31ewl
The keywords public, private and protected(also known as default) are called as access modifiers. With the help of these access modifiers we can access to the variables which are declared inside a class and outside a method or a constructor.
*PUBLIC* : If the access modifier is public, then the variable declared with public can be accessed by any one through out the application.
*PRIVATE* : If the access modifier is private, then the variable declared with private can be accessed with in the class in which it was declared.
*PROTECTED* : If the access modifier is protected, then the variable declared with protected can be accessed with in the package only.
*NOTE
: The variables which are declared either in private or protected can be accessed by using a OOP concept called as Inheritance
Sonali7
The keywords public, protected, default, and private are called the access modifiers. These access modifiers determines the scope of the classes, interfaces, variables, methods, constructors, data members, and the setter methods.
If the access modifier is public*,then it is accessible by all the classes.
If the access modifier is *protected*,then it is accessible by all the classes in the same package and within sub-classes in other packages(through inheritance).
If the access modifier is *default*,then it is accessible by all the classes in the same package.
If the access modifier is *private
,then it is accessible within the same class as it is declared.

Login / Signup to Answer the Question.