Java Basics Access modifiers

In Java, access modifiers are keywords that are used to restrict the visibility or accessibility of classes, methods, and attributes. There are four access modifiers in Java:

1. Public: This access modifier allows a class, method, or attribute to be accessed from anywhere in the program. For example:

public class Person {
    public String name; // public attribute
    public void sayHello() { // public method
        System.out.println("Hello!");
    }
}

This declares a public class called `Person` with a public attribute `name` and a public method `sayHello`.

2. Private: This access modifier restricts a class, method, or attribute to be accessed only within the same class. For example:

public class Person {
    private String name; // private attribute
    private void sayHello() { // private method
        System.out.println("Hello!");
    }
}

This declares a public class called `Person` with a private attribute `name` and a private method `sayHello`.

3. Protected: This access modifier allows a class, method, or attribute to be accessed within the same package or by a subclass in a different package. For example:

public class Person {
    protected String name; // protected attribute
    protected void sayHello() { // protected method
        System.out.println("Hello!");
    }
}

This declares a public class called `Person` with a protected attribute `name` and a protected method `sayHello`.

4. Default: This access modifier, also known as package-private, allows a class, method, or attribute to be accessed only within the same package. If no access modifier is specified, the default access modifier is used. For example:

class Person {
    String name; // default attribute
    void sayHello() { // default method
        System.out.println("Hello!");
    }
}

This declares a class called `Person` with a default attribute `name` and a default method `sayHello`.

Access modifiers are used to control the visibility and accessibility of classes, methods, and attributes in a program. By using access modifiers, you can ensure that your code is secure, encapsulated, and easy to maintain.