posted 20 years ago
i'm getting confused on how to approach the access modifiers of subclasses. Why isn't there an access modifier that only allows the current class and it's subclasses access to the member? It seems many people think that protected does this, but protected also allows access by other classes in the same package.
contrived example: Say there is a base class called Vehicle. It has a member variable called numWheels. Subclasses of Vehicle should be able to set the number of wheels, but other classes should be able to get the number of wheels, but not set it. How should this be handled?
In example 1, public access to numWheels obviously isn't correct. However, default package access to numWheels would allow any other class in the package to change the number of wheels that Car has. Same with protected. This means that if class Road (or Bicycle or Moped, etc) was in the same package, it could change the number of wheels on a car!
The next thought is to have numWheels marked private, and then make a protected setNumWheels(int) method. But, this puts the code at same logical point as before: classes within the same package can call the protected methods.
so, what is the solution? how do we allow only the subclasses access to a member variable or function? hopefully this is clear and i'm not missing something obvious here...
thanks,
Jon
use the [CODE] tags - it makes it much easier for people to help you.