aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reference Variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reference Variable" Watch "Reference Variable" New topic
Author

Reference Variable

Hitesh Ankolekar
Greenhorn

Joined: Aug 22, 2007
Posts: 7
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.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy Hitesh,

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.



Yours,
Bu.


all events occur in real time
 
Don't get me started about those stupid light bulbs.
 
subject: Reference Variable