Avatar ·

What is the difference between public, protected, package-private and private in Java?

Hi everyone! I just started learning Java and I can't figure out access modifiers. I kind of understand that they control the visibility of classes, methods and fields, but in practice I keep getting confused.

\n\n

For example, I have this code:

\n\n
public class Animal {\n    public String name;\n    protected int age;\n    String breed; // package-private\n    private String id;\n    \n    public void makeSound() {\n        System.out.println("Some sound");\n    }\n    \n    protected void sleep() {\n        System.out.println("Sleeping...");\n    }\n    \n    void eat() {\n        System.out.println("Eating...");\n    }\n    \n    private void breathe() {\n        System.out.println("Breathing...");\n    }\n}\n\npublic class Dog extends Animal {\n    public void testAcc