Java private keyword examples
- Details
- Written by Nam Ha Minh
- Last Updated on 19 August 2019   |   Print Email
In Java, the private keyword is an access modifier that can be applied to method, member variable and inner class.
1. private method in Java
If a method marked as private, it cannot be invoked from outside of the class it is declared. In other words, the private method is available to the enclosing class. For example:
class A { private void foo() { } void bar() { foo(); // okay, no problem! } } class B { void woo() { A a = new A(); a.foo(); // Oh no! since foo() is private } }
2. private variable in Java
The private access modifier can also be applied to member variables which are declared within a class. Like private method, a private variable can be accessed only from within its enclosing class. For example:
class A { private int number; void bar() { number = 10; // OK } } class B { void foo() { A a = new A(); a.number = 10. // Oh no! since number is private } }
3. private inner class in Java
An inner class is one that is declared inside another class. An inner class can be declared as private thus it can be accessed only from within the enclosing class, like private method and private variable. For example
class A { private class SubA { // inner class } void bar() { SubA obj = new SubA(); // OK } } class B { void foo() { A.SubA a = new A.SubA(); // Oh no! since SubA is private } }
Related keyword: public and protected. See all keywords in Java.
Related Topics:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments