Re: Core java fundamental help



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



.