Javatpoint Logo
Javatpoint Logo

Java private keyword

A Java private keyword is an access modifier. It can be assigned to variables, methods, and inner classes. It is the most restricted type of access modifier.

Points to remember

  • The private access modifier is accessible only within the same class.
  • We can't assign private to outer class and interface.
  • The best use of private keyword is to create a fully encapsulated class in Java by making all the data members of that class private.
  • If we make any class constructor private, we cannot create the instance of that class from outside the class.
  • If we are overriding any method, overridden method (i.e., declared in the subclass) must not be more restrictive.
  • According to the previous point, if we assign a private modifier to any method or variable, that method or variable can be overridden to sub-class using all type of access modifiers. However, still, we can't invoke private method outside the class.

Examples of private keyword

Example 1

Let's see an example to determine whether the private variable is accessible or not outside the class.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The field A.msg is not visible

Example 2

Let's see an example to determine whether the private method is accessible or not outside the class.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The method display() from the type A is not visible

Example 3

Let's see an example to determine whether we can assign the private modifier to the outer class.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 

Example 4

In the above example, we learn that the private method can't be invoked outside the class. Here, we call the private method from outside the class by changing the runtime behavior of that class.

Output:

private method is invoked

Example 5

Let's see an example to determine whether we create the instance of private constructor outside the class.

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The constructor A(String) is not visible

Example 6

In this example, the private method is overridden to sub-class using default access modifier. However, still, we are not allowed to invoke parent class method from sub-class.

Output:

child class method

Example 7

Let's see the real use of private keyword with the help of an example.

Output:

101 John William 25
Next TopicJava Keywords




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA