javamethodsdeclarationpublic

Should a Java method be declared public?


What is the difference between declaring a method public versus leaving it blank (default)?

void eat() {
  System.out.println("This food is great");
}

public void eat() {
  System.out.println("This food is great");
}

Solution

  • public - anyone, everywhere

    default(no modifiers) - only in package and in this class


    You can call method with public modifiers from another class / subclass(child-class) / another package / module (if dependency exist)

    Otherwise, default - you can call this method only from this class( inside calls) and from another package