Access Control in java|| Private access specifier in java || Public access specifier in java.

 Access Control:



You can control what parts of a program can access the members of a class. Java supplies a rich set of access specifiers to control this access. Java’s access specifiers are public, private, and protected.

private

When a member of a class is specified as private, then that member can only be accessed by other members of its class.

public

When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package. You can understand why main( ) has always been preceded by the public specifier. It is called by code that is outside the program—that is, by the Java run-time system.

Syntax:
class className
{
access specifier type varName;
access specifier returnType methodName(parameterList)
{ /* method Body */ }
}

Examples:

class Circle
{
private double radius;
Circle(double radius) //Constructor
{ this.radius = radius; }
private double calcArea() //private method
{
return (radius * radius) * 3.142857;
}
void showArea() //public method
{
System.out.println("Area : " + calcArea());
}
}
class circleTest
{
public static void main(String args[])
{
Circle myCircle = new Circle(3.9);
myCircle.showArea();
//myCircle.calcArea(); //Error calcArea is private to Circle class
}
}

Post a Comment

Please do not enter any spam link in the comment box