aspose file tools*
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Inheritance query" Watch "Inheritance query" New topic
Author

Inheritance query

manishkumarlal cs
Greenhorn

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;
A1.valueInt();
B1.valueInt();
System.out.println("........."+A1.i);
System.out.println("........."+B1.i);

}

}

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
.........0
.........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
Greenhorn

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

Joined: Oct 20, 2005
Posts: 257

Hello,

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.
 
 
subject: Inheritance query