01-Mar-2021 Access Specifiers in Java
01-Mar-2021 Access Specifiers in Java
SPECIFIERS
IN
JAVA
ACCESS SPECIFIERS IN JAVA
In java we have four Access Specifiers and they are listed below
1. public
2. private
3. protected
4. default(no specifier)
PUBLIC SPECIFIERS
● Classes, methods, and fields declared as public can be accessed from any class in
the Java program, whether these classes are in the same package or in another
package.
Example :
public class Demo {
// public class public x, y, size;
// public instance variables
}
PRIVATE SPECIFIERS
● private methods and fields are not visible within subclasses and are not inherited by
subclasses. So, the private access specifier is opposite to the public access
specifier
● Using Private Specifier we can achieve encapsulation and hide data from the
outside world
EXAMPLE
● Methods and fields declared as protected can only be accessed by the subclasses
in other package or any class within the package of the protected members' class
● When you don't set access specifier for the element, it will follow the default
accessibility level
● The class will be accessible to other classes in the same package but will be
inaccessible to classes outside the package
● When we say that a class is inaccessible, it simply means that we cannot create an
object of that class or declare a variable of that class type