Difference between public, protected, package-private (default) and private in Java
Hello everyone! I just started learning Java and can't figure out access modifiers. I've read the theory, but in practice I constantly get confused about when to use `public` and when to use `private`.\n\nFor example, I have this code:\n\n```java\npublic class Animal {\n public String name = "Unknown";\n protected int age = 5;\n String breed = "Mixed"; // package-private\n private String id = "A123";\n \n public void showInfo() {\n System.out.println("Name: " + name);\n System.out.println("Age: " + age);\n System.out.println("Breed: " + breed);\n System.out.println("ID: " + id);\n }\n}\n```\n\nIn another class within the same package, I can access `name`, `age` and `breed`, but not `id`. And if I create a subclass in another package, I can use
No answers yet.
Log in to leave an answer