Java private keywordA 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
Examples of private keywordExample 1Let'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 2Let'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 3Let'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 4In 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 5Let'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 6In 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 7Let's see the real use of private keyword with the help of an example. Output: 101 John William 25
Next TopicJava Keywords
|