Now I have another class DataInput that implements DataStorage and I want to make the dataObject private and put in accessor methods to get to the dataObject. But I also remember reading something that said, during inheritance you can not make the scope of the method (and variable?) more narrow. Meaning if a method was defined as default in the parent class, the subclass can not override that method to give it private access all of a sudden.
Now a couple of questions with this...does that rule only apply to subclassing (that is with extends) or does it also apply to implementing interfaces. Second question, I am pretty sure that rule applies to methods that are being overriden, but does it also apply to variables in an interface...because if that is the case, I can't re-declare the variable in the class that implements the interface to be private...and then there is no way to protect that variable.
By the way I did re-declare the variable in the subclass (implementing class) and declared it as a private, and it works...but I'm still trying to figure out the general rule.
Originally posted by Wilson Mui:
I am creating a DataStorage interface with a member variable (can I call it a member variable when it is in an interface?) called dataObject. From what I remember, and what the compiler is telling me, the scope declarations "private," or "protected" can not be used on either methods or member variables in an interface.
You can't actually call it a member variable, because (at least to me) that semantically states that the variable belongs to some instance of the class. Even if you do not declare your variables in interfaces as static and final, the compiler will do so for you--meaning that there will be only one instance of said variable. Implementing the interface does not add the variable to your class.
And, yes, the non-narrowing of scope applies to variables as well as methods, but not to static variables. Since your methods in the interface are (implicitly) static, your classes can override and narrow the scope.
But if it is final, does it mean I can re-declare that same variable name within the class that implemented the interface? (i.e interface car, class Honda implements car, and car has variable color, can I declare a variable color in Honda as well). I believe I did that, so I guess I answered my own question, but I want to make sure that that what I did was indeed overriding the variable.
So is it safe to say then that there I shouldn't declare a variable within an interface, unless I imply to be static...which, personally, is very rare.