0

I wonder if there is any difference if I declare the method as public or leave it undeclared like that :

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

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

Does it have any crucial value to it?

  • 1
    See the basic difference between [public and default](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private) access specifiers – SparkOn Jul 08 '14 at 15:16

4 Answers4

0

Member functions are package-private by default. See: access modifiers. There is a crucial difference (although to a beginner, the distinction between public and package-private may not be immediately obvious). Understanding access modifiers is crucial in any OO programming language.

linguamachina
  • 5,785
  • 1
  • 22
  • 22
0

From java docs (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes ...)

I believe this is called package if you explicitly state it

0

A Java method can be declared with one of four different access levels: public, protected, default (i.e. no explicit access level, also called package-private), and private.

A public method can be called by any object, while a package-private method can only be called by instances of classes which are defined in the same package as the receiving object's class.

Jacob Raihle
  • 3,720
  • 18
  • 34
0

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

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119