access hidden member through object refrense

class amit {

int a=2;

void show(){

System.out.println("hi how r u");

}

}

public class aseem extends amit {

int a=21;

public static void main(String[] args) {

amit obj=new aseem();

System.out.println( );

obj.show();

System.out.println(obj.a);

}

public void show(){

System.out.println("i am fine");

}

}

why the output is

2

i am fine

can any body explain that

[491 byte] By [aseem_ananda] at [2007-11-26 20:42:51]
# 1

When you use inheritance the compiler looks at the type of the object when calling a method. Your reference is of type amit, but your object is of type aseem. So the method of aseem is called.

However be carefull, if you use method overloading, the compiler uses the type of the reference. An example based on your classes, if you have a class containing following methods:

void print(aseem someAseem) {

System.out.println("Aseem is fine");

}

void print(amit someAmit) {

System.out.println("How is amit?");

}

aseem a = new aseem();

someclass.print(a);

amit b = new aseem();

someclass.print(b);

would give the output:

Aseem is fine

How is Amit?

Peetzorea at 2007-7-10 2:02:49 > top of Java-index,Java Essentials,New To Java...
# 2

Polymorphic method invocations apply only to instance methods. You can

always refer to an object with a more general reference variable type (a superclass

or interface), but at runtime, the ONLY things that are dynamically selected

based on the actual object (rather than the reference type) are instance methods.

Not static methods. Not variables. Only overridden instance methods are

dynamically invoked based on the real object's type.

Peetzorea at 2007-7-10 2:02:49 > top of Java-index,Java Essentials,New To Java...
# 3

Only ordinary methods calls can be polymorphic. The access to a field is resolved at compile time.

When a derived object is upcast to a base class reference the field accesses are resolved at compile time and hence it isn't polymorphic.

This is one reason why it is better to declare the fields as private, as it prevents the derived class from inheriting any class fields and hence avoid any confusion when the fields with the same name are declared or used in the derived class.

(Courtesy : Thinking In Java by Bruce Eckel)

qUesT_foR_knOwLeDgea at 2007-7-10 2:02:49 > top of Java-index,Java Essentials,New To Java...