my dog learned polymorphism*
The moose likes Java in General and the fly likes Inheritance query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance query" Watch "Inheritance query" New topic

Inheritance query

manishkumarlal cs

Joined: Oct 25, 2005
Posts: 11
Please check the following code

package Inheritance;

public class TestInheritance1 {
public static void main(String[] args)
A A1 = new A();
B B1 = new B();

A1 = B1;



class A
int i=0;

public void valueInt()

System.out.println("Value of i from class A:" + i);

class B extends A
int i = 5;
public void valueInt()

System.out.println("Value of i from class B :" + i);



Its giving the o/p as:

Value of i from class B :5
Value of i from class B :5

When we have assigned A1=B1, then why A1.i and A1.valueInt() are giving different values?
Srikanth Basa
Ranch Hand

Joined: Jun 06, 2005
Posts: 241
Aha the old classic problem of which one will be invoked.

Please note that when you call a method on an object, the method is invoked based on the objects Runtime type (i.e. the actual object pointed to by the reference variable).

Whereas when you access a variable, the variable picked up by using the reference type (and not the Runtime type of the actual object)

Thats the reason why you get to see two different values for method vs variable.
manishkumarlal cs

Joined: Oct 25, 2005
Posts: 11
Thank you,
Can you please elaborate on this.
Srinivas Kalvala
Ranch Hand

Joined: Oct 20, 2005
Posts: 257


The public & defualt instance attributes are always referenced by type but not run time reference.

The methods are always depends on the runtime reference but not type.

Let me put in clear way:

class A{int i;methodI();}
class B extends A{int i;methodI();}

A a=new A();
B b=new B();

a=b; --------> a.methodI() will refere b reference method
but --------> a.i will refer the type which is A so it will print A i value.
I agree. Here's the link:
subject: Inheritance query
Similar Threads
why this is not compiling
Is this method available..?
richard baldwin tutorial on threads
fwd or backward ,don't know which reference??
how to swap two integers inside a function ?