Way2Java

Java Made Simple: What is Java private method?

Java private method accessibility restrictions and overriding permissions are given. Go on read.

"private" is known as access specifier in Java. Like other specifiers, private is a keyword. An access specifier specifies the access to other classes belonging to the same package or other packages.

The private access specifier can be applied to instance variables and methods but not to classes and local variables. A private method can be accessed by the same class and within the class itself. It is not possible to call by other classes by composition. Even subclasses cannot access private method. "private" places maximum restrictions among all access specifiers in Java.

In the following private method code, display() is declared private and show() as public. The other class Demo cannot call display() but can call show().

class Test
{
  private void display()
  {
    System.out.println("Hello 1");
  }
  public void show()
  {
    System.out.println("Hello 2");
  }
}
public class Demo
{
  public static void main(String args[])
  {
    Test t1 = new Test();     
    // t1.display();	                // error, as display() is private in Test
    t1.show();	// works fine as show() is public
  }
}

It is the case with private variables also.

Variables and methods of a class are known as members of a class. Constructors are not members of a class. Why? A member can be called with an object where as constructor cannot be. You should use access with constructor but not call. That is, You can access a constructor but you cannot call a constructor. You can access a constructor by creating an object only.