I have the following class (example):
public class Dog { int numberOfTeeth; public Dog() { countTeeth(); } private void countTeeth() { this.numberOfTeeth = 5;
After I create the dog’s object, the number of teeth calculated must be calculated. I would like to have access to this value without being able to change it outside the class itself.
Dog d = new Dog(); int dogTeeth = d.numberOfTeeth;
However, I cannot figure out which access modifier will allow me to do this. I tried all of the following:
If I create numberOfTeeth private , I cannot access it.
If I create a numberOfTeeth protected internal , I can change this value outside the class.
If I create a numberOfTeeth internal , I can change this value outside the class.
If I create numberOfTeeth protected , I cannot access it.
If I numberOfTeeth public , I can change this value outside the class.
I also tried to make it readonly , but then could not install it outside the constructor.
Is there any access modifier that will allow me to do this? Or is there some other way to implement this protection?
source share