Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
The following rules for inherited methods are enforced −
Methods declared public in a superclass also must be public in all subclasses.
Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
Methods declared private are not inherited at all, so there is no rule for them.
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.
The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it.
ExampleThe following class uses protected access control. We've used a protected field as shown below −
package com.tutorialspoint; public class JavaTester { protected String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } public void print() { System.out.println(this.format); } public static void main(String args[]) { JavaTester tester = new JavaTester(); tester.format = "XML"; } }Output
XML
Here, the format variable of the Logger class is protected, so this variable can be accessed directly using just a reference of the class Logger.
But as a best practice, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.
Following is another example of protected access identifier. We've defined a protected field in super class. If a field/method is protected then it can be inherited by subclass.
Examplepackage com.tutorialspoint; class Logger { protected String format; public void print() { System.out.println(this.format); } } public class JavaTester extends Logger { public static void main(String args[]) { JavaTester tester = new JavaTester(); tester.format = "XML"; tester.print(); } }Output
XML
java_basic_syntax.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4