Thursday 27 April 2017

Private Keyword in Java

Private Keyword in Java

Private is the most restrictive access level. A private member is accessible only to the class in which it is defined. You should use this access to declare members that you are going to use within the class only. This includes variables that contain information if it is accessed by an outsider could put the object in an inconsistent state, or methods, if invoked by an outsider, could jeopardize the state of the object or the program in which it is running. You can see private members like secrets you never tell anybody.
To declare a private member, use the private keyword in its declaration. The following class contains one private member variable and one private method:
class First
{
private int MyPrivate; // private data member
private void privateMethod() // private member function
{
System.out.println("Inside privateMethod");
}
}
Objects of class First can access or modify the MyPrivate variable and can invoke privateMethod.Objects of other than class First cannot access or modify MyPrivate variable and cannot invoke privateMethod . For example, the Second class defined here:
class Second {
void accessMethod() {
First a = new First();
a. MyPrivate = 51; // illegal
a.privateMethod(); // illegal
}
}
cannot access the MyPrivate variable or invoke privateMethod of the object of First.
If you are attempting to access a method to which it does not have access in your program, you will see a compiler error like this:
Second.java:12: No method matching privateMethod()
found in class First.
a.privateMethod(); // illegal
1 error
One very interesting question can be asked, “whether one object of class First can access the private members of another object of class First”. The answer to this question is given by the following example. Suppose the First class contained an instance method that compared the current First object (this) to another object based on their iamprivate variables:
class Alpha
{
private int MyPrivate;
boolean isEqualTo (First anotherObject)
{
if (this. MyPrivate == anotherobject. MyPrivate)
return true;
else
return false;
}
}
This is perfectly legal. Objects of the same type have access to one another’s private members. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level.

Visit our site for Registration java coaching in Jaipur

0 comments:

Post a Comment