×

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained.

Privately declared constructors, variables, and methods are only accessible within the declared class. The most limited access level is private access modifier. Interfaces and classes cannot be private. If the class contains public getter methods, private variables can be accessed from outside the class. The primary means by which an object isolates itself and conceals data from the outside world is using the private modifier.

In a Java code block, the word "private" is used to indicate that a class, function, or variable has limited accessibility. A class, method, or variable in a program that is designated as private signifies that, unlike a public method, it cannot be accessed by anybody outside of the class or method. Java normally uses the Private keyword in a fully contained class.

Working of Private Keyword

Java's "Private Keyword" function only applies to that class. Outside of the class(es) and interface(s), it is inoperative. If the class members are PRIVATE and the class is entirely enclosed, the Private Keyword works nicely.

Using some access modifiers, a private keyword, variable, or method can also be overridden by a subclass or subclasses to call a PRIVATE METHOD outside of the class. By utilising simply, the Private Access Modifiers, Private Keyword can now also be used outside of the class.

Important Points about Private Keyword:

  • Only members of the same class have access to the private access modifier.
  • We are unable to make an interface and outer class private.
  • The best way to use the private keyword in Java is to entirely encapsulate a class by making all its data members private.
  • Making a class' function Object () {[native code]} private prevents others from making instances of that class.
  • Any method that is being overridden must not be more restrictive than the original method, which must be stated in the subclass.
  • In accordance with the previous point, any method or variable that has a private modifier applied to it can be overridden by a subclass using any form of access modifier. We are still unable to call private methods outside of the class, though.

Examples of Java Private Keyword

Example 1:

Using an example, you can tell whether a private variable is available outside of the class or not.

class AP
{  
 private String mss="accessing the private variable outside the class";
}  
public class PrivateEx1 {  
public static void main (String [] s) {  
    AP a=new AP ();
   System.out.println(a.mss);


}  
}  

Output:

Error: Unresolved compilation problem: 
The field A.msg is not visible

Example 2:

Using an example, you can determine whether a private method is available outside of the class.

class AP
{  
private void disp ()  
 {  
     System.out.println("accessing private keyword ouside of the class ");
 }         
}  
public class PrivateEx2 {  
public static void main (String [] s) {  
    Ap a=new AP ();
a. disp ();


}  
}  

Output:

Error: Unresolved problem compilation

Example 3:

Take the following example into consideration to determine if we can grant the outer class the private modifier.

private class PrivateEx3 {  
void disp ()  
{  
    System.out.println("accessing outer private class");
}  
public static void main (String [] s) {  
    PrivateEx3 p=new PrivateEx3();
p. disp();


}  
}  

Output:

Error: Unresolved problem of compilation

Example 4:

The private method cannot be called from outside the class, as demonstrated in the example above. By altering the runtime behavior of the class in this case, we can invoke the private function from outside the class.

import java. langs. reflect. Method;


class AA {    
  private void disp()  
  {  
      System.out.println("implementation of private method is done");
  }    
}      
public class PrivateEx4{    
public static void main (String [] s) throwsException {


    Class c = Class.forName("AA");
    Object o= c. newInstance ();
    Method mm =c. getMethod ("dispplaying", null);
    mm.setAccessible(true);
    m.invoke (o, null);
}    
}    

Output of the program is given by:

Implementation of private method is done

Example 5:

To determine whether we use the private function Object () { [native code] } instance outside of the class, consider an example.

class AA
{  
 String mss;
private AA(String mss)  
 {  
    this.mss=mss;
 }  
void disp()  
{  
    System.out.println(mss);
}  


}  
public class PrivateEx5 {  
public static void main (String [] s) {  
    AAhh=new AA ("implementing the constructors outside the class");
hh. disp ();
}  
}  

Example 6:

In this illustration, the default access modifier is used to subclass the private method. But even so, calling parent class methods from subclasses is not permitted.

class AA {   
private void mss ()  
{  
    System.out.println("method of parent class");
}    
}    


public class PrivateEx6 extends AA {  


void mss ()  
{  
    System.out.println("method of child class");


}  
 public static void main (String s []) {
     PrivateExample6 obj=new PrivateEx6();
obj.mss ();
   }    
}   

Output:

Method of child class

Related Topics

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Armstrong Number Program in Java

Armstrong Number Program in Java: A positive number is called an Armstrong number if the sum of the cube of each digit is equal to the number itself. There are...

6 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Java String lastIndexOf() method

Java String lastIndexOf() method returns last index of character or substring in a String. Syntax: Method Description int lastIndexOf(int ch)It returns last index position for the given char valueint lastIndexOf(int ch, int...

2 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java Math max() Method

The max() method of Math class returns the greater of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double max(double a, double b)public...

2 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

3 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

How to add 24 Hours to Date in Java?

In this tutorial, we will learn how to add 24 hours to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.