Re: Cannot override protected fields
On Jun 15, 7:53 pm, Roedy Green <see_website@mindprod.com.invalid>
wrote:
On Fri, 15 Jun 2007 17:44:19 -0000, DeeGoogle <k1205@hotmail.com>
wrote, quoted or indirectly quoted someone who said :
public class ParentForm {
protected String name = "ParentForm";
protected String getName(){return name;}
}
public class ChildForm extends ParentForm{
protected String name = "ChildForm"; //I am trying to override
the field value but reuse the method from parent.
}
public class Test {
public static void main(String[] args) {
System.out.println((new ParentForm()).getName());
System.out.println((new ChildForm()).getName());
There is no need for two different name fields, just two different
methods. The only time you would get shadowing is by accident. So the
Thanks all, for your responses. I understand there are different ways
to get around this - one being putting some code in the constructor as
someone else suggested. I was not asking for solutions or definitions
or rules - just asking why java(and even C#) has been designed that
way with instance variables- what they had in mind.
Here is a hypothetical scenario. Assume the getName() method in the
parent had a hundred lines of code in it before it returned the the
value of its variable 'name'. Let us say, I am now asked to write a
child class "ChildForm" that does pretty much the same thing as the
parent except return the value "ChildForm" and am not allowed (for
some reason) to touch/modify the ParentForm class written long ago by
someone else(so there is no point in saying 'youre design is bad'
etc.- just deal with it). Now had they allowed overriding of instance
variables, all I had to do was create this Child form with EXACTLY one
line of code - that too a DECLARATION (=no code) of the variable
'name' assigned with a value of "ChildForm" refer my example. No more
code, no work arounds, constructors, wrapper etc. Since the designers
of java etc did not allow that, my only option is to write extra code,
one of them being doing a cut and paste the 100 lines of code from the
parent as is into the child class. Why be forced into such
'workarounds' ?
PS: Again, I am not asking for a workaround or a solution - I am just
trying to learn the purpose of such a design of java/c#. Are there
cons that overshadow the pro I described above ? Or do you contend the
fact that it is a pro at all ?