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.
Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
ExampleThe following class uses private access control. We've used a private field as shown below −
package com.tutorialspoint; public class JavaTester { private 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.setFormat("XML"); tester.print(); } }Output
XML
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.
So, 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 private access identifier. We've defined a private field in super class. If a field/method is private then it cannot be inherited by subclass.
Examplepackage com.tutorialspoint; class Logger { private 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 class JavaTester extends Logger { public static void main(String args[]) { JavaTester tester = new JavaTester(); tester.setFormat("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