пятница, 5 января 2024 г.

Access Modifiers in Java

Access modifiers control the visibility of classes, fields, methods, and constructors. Java has four levels:


1. public

Accessible from anywhere — any class, in any package.

public class Car {
public String model;
public void drive() { }
}

2. protected

Accessible within the same package, plus subclasses in other packages (via inheritance).

class Animal {
protected String name;
protected void makeSound() { }
}


3. default (no modifier)

Accessible only within the same package. If you don't write any modifier, this is what you get.

class Utility {
int helperValue; // default access
void helperMethod() { } // default access
}


4. private

Accessible only within the same class. Not visible to subclasses or anything outside.

class BankAccount {
private double balance;
private void logTransaction() { }
}


Where They Apply

  • Top-level classes/interfaces: only public or default (no private/protected)
  • Members (fields, methods, constructors, nested classes): all four modifiers apply

Комментариев нет:

Отправить комментарий