Menu

1 / 3

Access Modifiers in Java

DEV Community·Divya Divya·7 months ago
#YerQL1Li
#beginners#java#programming#tutorial#package
Reading 0:00
15s threshold

Every Java developer writes classes, methods, and fields. But who should be allowed to use them? Access modifiers answer exactly that — they control visibility, enforce encapsulation, and form the foundation of clean API design.

Java has four:

Default (Package-private)

Private

Protected

Public

Let's break each one down.

Default Access Modifier

If no access modifier is specified, the member has default (package-private) access and can only be accessed within the same package.This means only classes within the same package can access it.

Example

class Car { String model ; // default access }

public class Main {

public static void main ( String [] args ){

Car c = new Car (); c . model = "Tesla" ; // accessible within the same package System . out . println ( c . model ); } }

Enter fullscreen mode

Exit fullscreen mode

Output

Private Access Modifier

The private access modifier is specified using the keyword private.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.