what is the difference between private and protected? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

what is the difference between private and protected?

11th Oct 2016, 7:14 PM
Punit Mahipal
4 Answers
+ 4
From the outside, private and protected look the same - that is, if you have a method that is either private or protected, you can't call it from outside the class. The difference shows once you throw inheritance into the mix. Let's consider // A dog. public class Dog{ public string name; } // Finds stray dogs from the street and keeps them in cages public class Kennel{ private Deque<Dog> dogs; public Kennel(){ dogs = new Deque<Dog>(); } public void findStrayDog(){ Dog dog = new Dog(); dog.name = "Unnamed Dog"; dogs.add(dog); } protected Dog getDog(){ return dogs.poll(); } } just fyi: A Deque is basically a list, `poll` get's the first element off that list :) Here, we have a public method called findStrayDog. So if somewhere else we were to do: Kennel k = new Kennel(); k.findStrayDog(); that would be totally fine and it would add one Dog to the List. If we tried to do the same with `dogs` or `getDog`, they would throw an error, since we can't access them from outside. So why make one protected and one private? Let's subclass Kennel: // best dog shop in town; it's a Kennel that sells dogs public class DogShop3000 extends Kennel{ // you can even give it a new name public Dog sellDog(string newname){ Dog d = getDog(); d.name = newname; return d; } } See how DogShop3000 can call `getDog()`? You can't access `getDog` from outside `Kennel`, but since you marked `getDog` as protected, subclasses will be able to access it! Still, DogShop3000 will not be able to directly access the list `dogs` - it is private, so not even subclasses can see it. So: private is stricter than protected is stricter than public. private and protected methods and fields can be useful when dealing with lots of subclasses, you can exactly define what they should be able to see and what not!
11th Oct 2016, 9:47 PM
Schindlabua
Schindlabua - avatar
+ 2
Private access modifier hides the variable or method from every class in its package. Protected access modifier is like public but restrics the method/variable to its subclasses.
11th Oct 2016, 9:46 PM
John Octubre
John Octubre - avatar
0
PRIVATE - If you declare it Private, then it will be highly secured. Nothing outside the declared class will be able to access it. PROTECTED - (this definition is copied) The protected modifier makes the marked thing (class, method, or field) available to some other class in some other package, only if said other class is a subclass of the class, where that protected-marked thing is declared.
12th Oct 2016, 12:15 PM
Chetan Sapra
Chetan Sapra - avatar
0
I wish this quesiton was marked as duplicate.
16th Oct 2016, 10:16 AM
Sławek Śpiewak
Sławek Śpiewak - avatar