Java Made Simple: What is Java private and private variable?

Private means purely private to that class. Private variable means can not be used by other class or even subclass. Given Example Screenshot Simple terms. Go on read.

In Java, "private" is a keyword known as access specifier. As an access specifier, private gives maximum restrictions and no permissions. In common sense and generally also, a private means purely private to that class. For example, a private variable means that can be used by that class only and not by any other class even it is a subclass of the same package.

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.

Following program illustrates private variable.
class Test
  private int marks = 50;
  public int rank = 2;
public class Demo
  public static void main(String args[])
    Test t1 = new Test();     
    // System.out.println(t1.marks);	// error, as marks is private in Test
    System.out.println(t1.rank);   	// works fine as rank is public

Following is compilation error message when comments are removed in main() for t1.marks.
private variable

As marks is private, it cannot be accessed or called by any other class. It can be used within Test class only (not shown in the code, you can try). It is not possible even Demo extends Test; that is subclasses also cannot access.

Leave a Comment

Your email address will not be published.