Declarations and Access Control
In Java, declarations and access control are used to specify how variables, methods, and classes can be accessed or used in a program.
A declaration is a statement that creates a variable, constant, or method in a program. It specifies the type and name of the variable or method, and optionally initializes it with a value. For example, the following code declares an integer variable named “x” and initializes it to the value 10:
int x = 10;
Access control is used to restrict the visibility or accessibility of variables, methods, or classes in a program. Java has four levels of access control: private, default, protected, and public.
Private: Variables or methods marked as private are only accessible within the same class. For example:
private int x;
private void doSomething() {
// code here
}
Default: Variables or methods that are not explicitly marked with an access control modifier are considered to have default access, which means they can only be accessed by other classes within the same package. For example:
int x; // default access
void doSomething() { // default access
// code here
}
Protected: Variables or methods marked as protected can be accessed by other classes in the same package, as well as by subclasses in any package. For example:
protected int x;
protected void doSomething() {
// code here
}
Public: Variables or methods marked as public can be accessed by any class in any package. For example:
public int x;
public void doSomething() {
// code here
}
In addition to these access control levels, Java also has two special access modifiers: final and static.
Final: When applied to a variable or method, the final keyword indicates that its value or implementation cannot be changed after initialization. For example:
final int x = 10; // x cannot be changed
final void doSomething() { // implementation cannot be changed
// code here
}
Static: When applied to a variable or method, the static keyword indicates that it belongs to the class rather than to instances of the class. This means that the variable or method can be accessed without creating an object of the class. For example:
static int x; // belongs to the class, not instances of the class
static void doSomething() { // can be called without creating an object of the class
// code here
}
Apply for Core Java Developer Certification Now!!
https://www.vskills.in/certification/certified-core-java-developer