Originally posted by vishnu prakash: Because t is a reference variable of class type Test and not a object type T
Only instance methods will be invoked based on object type. Instance variables will be invoked based on class type.
i didn't get the point here....
why in System.out.println(t.i+" "+t.j+" "+t.k);
t.i is producing 2 and not 1
as t is a reference variable fo Test it will call the instance variable from Test class ( this part is clear ) but when calling t.i (from Test) which intun is calling fun() ...according to result the method from class T is calling
i know you will say as object is of type T it will call method from class T but my confusion is that when i=fun(); is invoked in super class Test how it how it will call fun() method from subclass...as it may not know that it exist...
so is the following is the final conclusion. ? so is this is a case that always and always subclass method will be called if object is of subclass....and call of method can be from any where in the package...
and variable of refernce type will be called ...even called from any where..
To understand how this code works, you need to understand polymorphism. Basically, polymorphism allows the program to decide which method to call at run-time. Sometimes this is called "late binding". Notice that polymorphism only works with methods; it doesn't work with data fields. This means that the line
can dynamically decide which version of fun() to called based on the objects actual type. However, when you have a line like
the compiler decides which variable is assigned the value. This means that the value of the variable i is dynamic (i.e. determined at runtime), but the value of the two k variables is static (i.e. determined at compile time).
Similarly, the compiler decides which k variable to access at compile time. This is why you only see the value from the parent class and not from the sub class. Since t is a reference to Test, the compiler only "sees" the parent class and its fields.
I'm sure this explanation is clear as mud. Please let me know if I need to clarify anything.