Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2007

Tip: Looking for answers? Try searching our database.

Cannot override protected fields

Thread view: 
DeeGoogle - 15 Jun 2007 18:44 GMT
I know this is not possible, but my question is why did they design it
that way:

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());
  }
}

Output:
ParentForm
ParentForm

I wanted to see "ChildForm" in the second line. Why do I have to
duplicate (literally cut and paste) the getName() method in the child
to achieve it ?

Can someone explain the concept I am missing ?
lithyum79@gmail.com - 15 Jun 2007 19:52 GMT
You know, that has nothing to do with protected fields. In fact the
same would be true if the fields were public.

What you might want is something like this:

public class ChildForm extends ParentForm {
   public ChildForm() {
       name = "ChildForm";
   }
}

This way, instead of declaring another member variable with the same
name as the parent class you assign the parent's name variable a new
value upon construction. :)

> I know this is not possible, but my question is why did they design it
> that way:
[quoted text clipped - 25 lines]
>
> Can someone explain the concept I am missing ?
Hoss Spence - 15 Jun 2007 22:52 GMT
On Jun 15, 12:52 pm, lithyu...@gmail.com wrote:
> You know, that has nothing to do with protected fields. In fact the
> same would be true if the fields were public.
[quoted text clipped - 41 lines]
>
> > Can someone explain the concept I am missing ?
Generally bad form to override instance variables. You want to define
them once in the super class and set them in the constructor or a
setter in the subclass.
Roedy Green - 16 Jun 2007 00:53 GMT
>public class ParentForm {
>     protected String name = "ParentForm";
[quoted text clipped - 10 lines]
>        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
two fields should be treated as if they had different names.

Shadowing is a dumb idea, but when somebody does it, I have an example
to explain what happens.  See
http://mindprod.com/jgloss/gotchas.html#OVERRIDE

--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
The Billboard Hot 100 - 16 Jun 2007 10:11 GMT
A subclass can't override fields of the superclass. A subclass can
override non-static methods that are defined in the superclass.
Protected fields should be avoided because it has potential to cause
the Fragile Base Class Problem as subclasses and classes in the same
package have access to these fields.

You can have access to it from the constructor simply using the "name"
filed also it is possible to use the keyword super to access it from
the subclass

public class ChildForm extends ParentForm{
  public ChildForm(){
             super.name = "ChildForm";
    }
}

Emre Simtay
DeeGoogle - 18 Jun 2007 20:31 GMT
On Jun 15, 7:53 pm, Roedy Green <see_website@mindprod.com.invalid>
wrote:

> >public class ParentForm {
> >     protected String name = "ParentForm";
[quoted text clipped - 13 lines]
> 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 ?
Twisted - 18 Jun 2007 21:31 GMT
> 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
[quoted text clipped - 4 lines]
> someone else(so there is no point in saying 'youre design is bad'
> etc.- just deal with it).

Then you use this:

public class ChildForm extends ParentForm {
   public String getName() {
       super.getName(); // Do whatever ParentForm.getName() does,
                        // but discard the return value "ParentForm"
       return "ChildForm";
   }
}

Mind you, in this scenario there seems to be no clean separation of
responsibilities, with getName() apparently doing more than one job.
If you inherited the maintenance of a codebase with an untouchable
class like the hypothetical ParentForm with its overly ambitious
getName() method, you'd do well to complain about it somewhere. :)
cyprian - 19 Jun 2007 15:42 GMT
> > 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
[quoted text clipped - 21 lines]
> class like the hypothetical ParentForm with its overly ambitious
> getName() method, you'd do well to complain about it somewhere. :)

this answer insightful. i didn't see an override of the getName()
method. in java, you don't access fields directly, it's against the
security features of java and against oop, instead, you use getters
and setters, override the getters and setters and you're rocking.
forget the fields.
DeeGoogle - 19 Jun 2007 20:45 GMT
> Then you use this:
>
[quoted text clipped - 12 lines]
> class like the hypothetical ParentForm with its overly ambitious
> getName() method, you'd do well to complain about it somewhere. :)

You are again giving me a solution/workaround, see ? My question is
'why' and not 'how'. I am not trying to solve a problem - merely
trying to understand it. Your solution requires writing logical code
(be it 2 lines) which is what I am trying to avoid by just declaring
an overriding variable in the child class (no offence meant).
Why didn't they allow us to simply override the field instead of
forcing us to override the method and write logic within that method
to achieve the purpose.
A simple declaration in the ChildForm.java should have sufficed like
this (saves you the call to super.getName() etc):
protected String name = "ChildForm"; //I am trying to override the
field value but reuse the method from parent.

But they (creators of java/c#) didn't let us do it. My question is
'why' ? Someone suggested it is against 'oop'.  Why so ?
Joshua Cranmer - 19 Jun 2007 23:38 GMT
> You are again giving me a solution/workaround, see ? My question is
> 'why' and not 'how'. I am not trying to solve a problem - merely trying
[quoted text clipped - 7 lines]
> But they (creators of java/c#) didn't let us do it. My question is 'why'
> ? Someone suggested it is against 'oop'.  Why so ?

The short answer: variables are statically bound whereas methods are
(most of the time) dynamically bound.

The long answer:
Imagine a class thusly, assuming that variables are polymorphic:
class Foo {
   protected int resources = 0; // there are ### resource handles
   void doSomething() {
       // ...
       counter++; // There is a new resource handle
       // ....
   }
}

class Bar extends Foo {
   private int resources = 0; // we are handling ### resources
   void doSomethingElse() {
       // ...
       counter++; // We are managing one more resource
   }
   void transaction() {
       doSomething();
       doSomethingElse();
   }
}

Clearly, calling transaction will start messing up the resource counters,
throwing stuff off. Polymorphic variables are inherently dangerous, as
people can, through lack of knowledge of API, innocuously wreak havoc.
Therefore, variables are made to be statically bound in all cases.

Even if variables are statically being defined, why not simply have the
redefinition of variable in a subclass "override" the definition in a
super class? Because one is really /redefining/ the variable. Any
property can only have one definition (think about it).

Which leaves the final case: why not use the simple assignment syntax
without definition? Because it is then arbitrary execution inside a block
where only definitions are permitted, and because it is very easy to
simply move the definition to a constructor.
DeeGoogle - 20 Jun 2007 15:52 GMT
> The short answer: variables are statically bound whereas methods are
> (most of the time) dynamically bound.
[quoted text clipped - 38 lines]
> where only definitions are permitted, and because it is very easy to
> simply move the definition to a constructor.

That was a beautiful answer with a great example. I think I am
beginning to understand the idea now. If I still have my doubts, I may
try to clarify further. But thanks for your reply ! This is the kind
of answer I was looking for - 5 stars.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.