Can anyone please explain the statement below (with example)
Reference variable can only of one type and once declared that type can never changed although the object it reference changes.
Also Reference variable can be reassigned to other objects except declared as final.
Joined: Aug 25, 2006
welcome to the Ranch!
About your question:
The variable "variable" is of type A. So you can invocate only methods of class A on it. In the first line of the main method, the A type variable is referencing an A type object, in the second line this changes, now it is referencing ("pointing to") a B type. Even though the object referenced by "variable" is of the sub type B now, you can not invocate a b_method using it. The line with comments would not compile if uncommented.
What you can do is casting, like in the last two lines. But here you produce a new variable "bvar" of type B and invocate the b_method using bvar.
This is meant when you say that a variable once assigned can never change its type. The object behind it can change its type, but because the variable still has its once-and-for-all type, you can use methods only declared (or inherited) in the class of the type with which the variable was declared as.