In Java, access modifiers (public, protected, package-private/default, and private) control the visibility and accessibility of classes, methods, and fields within different scopes. Here's an explanation of each modifier with examples:
public:- Members declared as
publicare accessible from any class and package. - There are no restrictions on access.
java- Members declared as
public class PublicExample {
public int publicVar = 10;
public void publicMethod() {
System.out.println("This is a public method.");
}
}
protected:
- Members declared as
protectedare accessible within the same package and subclasses (even if the subclass is in a different package). - Subclasses can access protected members of their superclass.
java
class Parent {
protected int protectedVar = 20;
}
public class Child extends Parent {
public void accessProtectedVar() {
System.out.println("Protected var from Child: " + protectedVar);
}
}
Package-Private (Default):
- If no access modifier is specified, the member is package-private (default).
- Members are accessible only within the same package.
java
class PackagePrivateExample {
int packagePrivateVar = 30;
}
private:
- Members declared as
privateare accessible only within the same class. - They are not visible or accessible from any other class or package.
java
public class PrivateExample { private int privateVar = 40; private void privateMethod() { System.out.println("This is a private method."); } }
Remember, access modifiers apply not only to classes and methods but also to fields. The access level of a member affects where it can be accessed from and provides encapsulation by restricting direct access.
Example: Putting It All Together:
java
package com.example;
class Parent {
int packagePrivateVar = 20;
protected int protectedVar = 30;
private int privateVar = 40;
}
public class Child extends Parent {
public void accessMembers() {
System.out.println("Package-Private Var: " + packagePrivateVar); // Accessible because in the same package
System.out.println("Protected Var: " + protectedVar); // Accessible because it's a subclass
// System.out.println("Private Var: " + privateVar); // Not accessible from Child
}
public static void main(String[] args) {
Child child = new Child();
child.accessMembers();
}
}
In this example, the Child class inherits the protected member from its Parent class and can access it. The package-private member is also accessible because the classes are in the same package. However, the private member is not accessible from Child.
Comments
Post a Comment