
Take for example the following markup. In this example, there are three methods, hello (public) and world (private) and main (public). Notice these methods all exist within the same class (Main). Since these methods are in the same class, setting the hello method as public and the world method as private will not impact the ability of the main method to use the hello and world methods. In this scenario, System.out.println should successfully print Hello and World.
public class Main {
public static void hello( ) {
System.out.println("Hello");
}
private static String world( ) {
return "World";
}
public static void main(String[] args) {
hello();
System.out.println(world());
}
}
Let's say you have two classes, foo and bar. Notice in the foo class that the world method is private. This means the world method can only be used instead of the foo class. Since the hello method is public, the hello method can be used in the bar class. However, since the world method is private, the world method cannot be used in the bar class.
public class foo {
public static void hello( ) {
System.out.println("Hello");
}
private static String world( ) {
return "World";
}
}
public class bar {
public static void main(String[] args) {
foo.hello();
System.out.println(foo.world());
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at