• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Reference Variable

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Is this the real life? Is this just fantasy? Is this a tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic