Java Access Modifiers - The Coding Shala
Home >> Learn Java >> Java Access Modifiers
Java Access Modifiers
Java Modifiers are used to control access mechanisms that mean it defines where we can access the class and its members based on its modifiers. In Java there are two types of modifiers:
- Access Modifiers
- Non Access Modifiers
In Java, we have 7 non-access modifiers. Java non-access modifiers are used to provide information about the behavior of class and its members. In Java, static, final, abstract, synchronized, transient, volatile, native are non-access modifiers.
Java Access Modifiers
The Java Access Modifiers specifies the accessibility or we can say they define the scope of a class, constructor, class members, methods, variables. There are four types of Java access modifiers:
Java Default Access Modifiers
When we don't use any access modifier with the class or its members, it is treated as a default access modifier by default. For default access modifiers we don't need to use any access modifier. The default access modifiers are only accessible within the package not outside it.
Example of Java Default Access Modifiers
The following example explains the Java Default access modifier:
In the above program inside package Pack2, we have declared class and method as default. Whenever we use Pack2 class inside Pack1 we will get a compile-time error.
Java Public Access Modifier
The Java public access modifiers are specified using the public keyword. A class, methods or data members that are declared as public can be accessed from anywhere.
Example of Java Public Access Modifier
The following example explains Java public access modifier:
Java Private Access Modifier
The Java private access modifier is specified using keyword private. A class, method or data members that are declared as private can only accessible within the same class in which they are declared not outside that class.
Example of Java Private Access Modifier
The following example explains Java private access modifiers:
NOTE: A class cannot be private.
Question: Can we create a private constrctor?
Answer: Yes, we can create a private constructor but when we do that then we can create an object of that class inside that class only not from any other class. The following example explains it:
Java Protected Access Modifier
The Java Protected Access Modifier is specified using the protected keyword. A class, method or data members are declared with a protected access modifier that can accessible within the same class or subclasses in another package.
Note: Class can not be protected.
Example of Java Protected Access Modifiers
The following example explains the java protected access modifiers:
Other Posts You May Like