Java Keyword Private

The reserved keyword private is used in the declaration of a method, variable, or inner Java class. A private member can only be accessed by other members of the same class.

Let’s start with a simple example that implements a private method. If we try and access loadsomething() method, the compiler will not be able to resolve it because it’s not visible to JavaCodeDepotClassTwo.

//JavaCodeDepot Sample 

class JavaCodeDepotClassOne {
 
    //This method is private and only accessible from this class
    private void loadSomething() { }
     
    public void unloadSomething() {
        
        //This works because it's the same class
        loadSomething();
    }
}
 
class JavaCodeDepotClassTwo {

    public void packSomething() {

        JavaCodeDepotClassOne jcdCOne = new JavaCodeDepotClassOne();

        jcdCOne.loadSomething();  /* Compiler will complain! */
    }
}


Let’s move onto an example that defines a private variable within a class. Trying to access jcdNumber from JavaCodeDepotClassTwo will result in the Java compiler complaining.

//JavaCodeDepot.com Sample 

class JavaCodeDepotClassOne {
 
    private int jcdNumber;
     
    public void unloadSomething() {
        
        //This works because it's the same class
        jcdNumber = 777;
    }
}
 
class JavaCodeDepotClassTwo {

    public void packSomething() {

        JavaCodeDepotClassOne jcdCOne = new JavaCodeDepotClassOne();

        jcdCOne.jcdNumber = 777;   /* Compiler will Complain *.
    }
}


The complete list of Java reserved keywords contains a total of 50 keywords and 3 literal words that are unable to be used as variable names.

Add a Comment

Your email address will not be published. Required fields are marked *