Java Access Modifiers
Access Modifiers in Java
Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and the outside world (other objects). Access modifiers are declared immediately before the type of a member variable or the return type of a method.
There are four access modifiers in java :
- default
- public
- protected
- private
Default Access Modifier
The default access modifier specifies that only classes in the same package can have access to a class's variables and methods. Class members with default access have a visibility limited to other classes within the same package. There is no actual keyword for declaring the default access modifier, it is applied by default in the absence of an access modifier.
Code for default access variable and member:
long length;Notice that neither the member variable nor the method supplies an access modifier, so each
void getLength() {
return length;
}
takes on the default access modifier implicitly.
public Access Modifier
The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global
visibility and can be accessed by any other object.
Sample Code for public member variables:
public int count;protected Access Modifier
public boolean valid;
The protected access modifier specifies that class members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses.
Sample code for protected variable and a protected method :
protected char Name;The private Access Modifier
protected char getName() {
return Name;
}
The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. This means that no other class has access to private class members, even subclasses.
Code example for private member variables:
private String firstName;Access to classes, constructors, methods and fields are regulated using access modifiers. Access modifiers in Java determine the visibility and the scope of the Java elements.
private double Value;
0 comments:
Post a Comment