Re: Core java fundamental help
- From: "Chris Uppal" <chris.uppal@xxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 31 Aug 2006 10:49:21 +0100
pras.vaidya wrote:
class SuperShow{
public String str ="Super";
That defines a field in SuperShow called "str".
class ExtendsShow extends SuperShow{
public String str = "Extend";
That defines /another/ field, in ExtendsShow, which is also called "str". So
now you have two fields with the same name (fields don't override in the way
that methods do).
Now, in:
ExtendsShow ext = new ExtendsShow();
SuperShow sup = ext;
System.out.println(sup.str);
when your code refers to the "str" field of an object only known to be of type
SuperShow, Java understands that to be a reference to the first field. If you
have written:
System.out.println(ext.str);
then Java would have taken it to be a reference to the second field. Even
though "sup" and "ext" refer to the same object, it has two separate fields
with the same name (but different values), so it makes a difference which one
the code refers to.
In general it's not a good to give a subclass a field with the same name as a
(visible) field in a superclass -- precisely because it is likely to confuse
you ;-)
-- chris
.
- References:
- Core java fundamental help
- From: pras.vaidya
- Core java fundamental help
- Prev by Date: Re: What replaces StringBufferInputStream
- Next by Date: Re: Where can I find SNTP server in Java?
- Previous by thread: Core java fundamental help
- Next by thread: Re: Core java fundamental help
- Index(es):