Access Modifiers
#Q
Access modifiers :: are keywords that determine the visibility and accessibility of classes, methods, and fields in a Java program.
#/Q
public
:: This is the least restrictive access modifier, and it allows a class, method, or field to be accessed from anywhere within the same package or from other packages.
#/Q
#Q
2. private
:: This is the most restrictive access modifier, and it restricts the visibility of a class member to only within the same class. This means that the member cannot be accessed from other classes.
#/Q
#Q
3. protected
:: This access modifier allows a class member to be accessed within the same package and also by subclasses, even if they are in different packages.
#/Q
#Q
4. default
(no modifier):: If no access modifier is specified, the member has package-private visibility, which means it can be accessed only within the same package.
#/Q
package com.example; // Assume this is the package name
// A class with public access modifier
public class PublicClass {
public void publicMethod() {
System.out.println("This is a public method.");
}
}
// A class with default (package-private) access modifier
class DefaultClass {
void defaultMethod() {
System.out.println("This is a default method.");
}
}
// Another class in the same package
class AnotherClassInSamePackage {
// A class member with private access modifier
private String privateField = "This is a private field.";
// A class member with protected access modifier
protected void protectedMethod() {
System.out.println("This is a protected method.");
}
}
// Subclass in a different package
package com.example.subpackage; // A different package
import com.example.AnotherClassInSamePackage;
public class SubclassInDifferentPackage extends AnotherClassInSamePackage {
public void accessProtectedMethod() {
protectedMethod(); // Accessing a protected method from a subclass in a different package
}
}
public class Main {
public static void main(String[] args) {
PublicClass publicObj = new PublicClass();
publicObj.publicMethod();
DefaultClass defaultObj = new DefaultClass();
defaultObj.defaultMethod();
AnotherClassInSamePackage anotherObj = new AnotherClassInSamePackage();
// Private fields and protected methods are not accessible here
SubclassInDifferentPackage subclassObj = new SubclassInDifferentPackage();
subclassObj.accessProtectedMethod();
}
}