0
0
Javaprogramming~15 mins

Default access modifier in Java

Choose your learning style8 modes available
menu_bookIntroduction

The default access modifier controls who can use a class, method, or variable when no specific access keyword is given. It helps keep parts of your code hidden from other parts, making your program safer and easier to manage.

When you want to share code only within the same package but not outside it.
When you want to hide details from other packages but allow access inside your package.
When you do not specify any access modifier and want Java to use the default.
When organizing code in packages and controlling visibility without using public or private.
regular_expressionSyntax
Java
class ClassName {
    // members here
}

// or

void methodName() {
    // method code
}

// or

int variableName;

The default access modifier is also called package-private because it allows access only within the same package.

No keyword is written before the class, method, or variable to use the default access modifier.

emoji_objectsExamples
line_end_arrow_notchThe class Car and its method startEngine have default access. They can be used only inside the same package.
Java
class Car {
    void startEngine() {
        System.out.println("Engine started");
    }
}
line_end_arrow_notchThe variable speed and method accelerate have default access because no modifier is given.
Java
class Vehicle {
    int speed = 0;

    void accelerate() {
        speed += 10;
    }
}
code_blocksSample Program

This program shows a class Bike with default access inside the vehicles package. The Main class creates a Bike object and calls its method. Both are in the same package, so access is allowed.

Java
package vehicles;

class Bike {
    void ringBell() {
        System.out.println("Ring ring!");
    }
}

public class Main {
    public static void main(String[] args) {
        Bike myBike = new Bike();
        myBike.ringBell();
    }
}
OutputSuccess
emoji_objectsImportant Notes
line_end_arrow_notch

Default access means no keyword is written before the class, method, or variable.

line_end_arrow_notch

Classes or members with default access are visible only inside the same package.

line_end_arrow_notch

Trying to access default members from another package will cause a compile error.

list_alt_checkSummary

The default access modifier allows access only within the same package.

No keyword is needed to use default access.

It helps organize code and control visibility without using public or private.