Cannot override protected fields

D

DeeGoogle

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 ?
 
L

lithyum79

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. :)

DeeGoogle escreveu:
 
H

Hoss Spence

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. :)

DeeGoogle escreveu:
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 ?
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.
 
R

Roedy Green

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
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
 
T

The Billboard Hot 100

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
 
D

DeeGoogle

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 ?
 
T

Twisted

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).

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. :)
 
C

cyprian

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. :)

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.
 
D

DeeGoogle

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. :)

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 ?
 
J

Joshua Cranmer

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.

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.
 
D

DeeGoogle

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.

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,186
Members
46,740
Latest member
JudsonFrie

Latest Threads

Top