Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance query

 
manishkumarlal cs
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 241
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you,
Can you please elaborate on this.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic