Protected vs Public in terms of Inheritance in Java
Protected vs Public in terms of Inheritance in Java
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
In 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.