In Java, the private keyword is an access modifier that can be applied to method, member variable and inner class.

 

1. private method in Java

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
    }
}

 

2. private variable in Java

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
    }
}

 

3. private inner class in Java

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.

 

Related Topics:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment

   


Comments 

#1Maxwell2018-01-27 18:02
Thanks for teaching me what a private comment is.
Quote