In Java, the private keyword is an access modifier that can be applied to method, member variable and inner class.
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 } }
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 } }
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.