Protected vs Public in terms of Inheritance in Java
Protected vs Public in terms of Inheritance in Java
372
18-Aug-2023
Updated on 19-Aug-2023
Aryan Kumar
19-Aug-2023In Java, the access modifiers
publicandprotectedare used to control the visibility of members of a class, such as variables, methods, and constructors.In terms of inheritance, the main difference between
publicandprotectedis thatprotectedmembers are only accessible to subclasses, even if the subclass is in a different package. This means thatprotectedmembers can be used to implement an inheritance hierarchy without exposing the implementation details to other classes.For example, let's say we have a class called
Animalwith aprotectedmethod calledgetSound(). This method returns the sound that the animal makes. We can then create a subclass ofAnimalcalledDog. TheDogclass can override thegetSound()method to return the sound that a dog makes. However, other classes outside of theAnimalandDogpackages cannot access thegetSound()method.Here is a table summarizing the visibility of
publicandprotectedmembers in Java:When choosing between
publicandprotected, you should consider the following factors:public.protected.private.