Lesson 30 +10 XP

Java Modifiers

Java Modifiers

Modifiers control how classes, methods, and attributes can be accessed or changed.

Access modifiers

ModifierEffect
publicAccessible everywhere
privateAccessible only inside the class
default (no keyword)Accessible in the same package
protectedAccessible in the same package and subclasses

Non-access modifiers

ModifierEffect
finalCannot be changed or extended
staticBelongs to the class, not objects
abstractCannot create objects; must be inherited

Final example

final class Vehicle {
  // a final class cannot be inherited
}

Private example

public class Main {
  private int x = 5;

  public static void main(String[] args) {
    Main myObj = new Main();
    // myObj.x is NOT accessible here from outside
  }
}

Choosing modifiers

  • Use private for internal data to protect it.
  • Use public for things other code should use.
  • Use final to prevent changes.

TL;DR

  • Access modifiers: public, private, protected, default.
  • Non-access modifiers: final, static, abstract.
  • private members are only visible inside their class.