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

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.

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 Reply

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