• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Plymorphism Explaination in K&B Book

 
Ranch Hand
Posts: 69
Netbeans IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,I just started my preparation for OCPJP.While studying the polymorphism topic(chapter 2 Exam objectives 5.2 in Kathy Sierra & Bert Bates book) I read these two sentences which I couldnt quite understand-

1.A reference variable can be of only one type , and once declared,that type can never be changed.
2.A reference is a variable,so it can be reassigned to other objects.

Can anyone explain me in detail ? An example would be of real help
Thanks in advance
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1.A reference variable can be of only one type , and once declared,that type can never be changed.

-- Dog d = new Dog(). Here d is the reference variable. d can be only of one type (Dog), it cannot be of type Dog and Cat and it cannot be changed from Dog to Cat any time. You can declare another reference variable say Cat d = new Cat(), in some other scope, but this is a different reference variable, even though the name is same.

2.A reference is a variable,so it can be reassigned to other objects.

Dog d1 = new Dog()
Dog d2 = new Dog();
d1 = d2 (A reference is a variable,so it can be reassigned to other objects.)

Remember the reassignment can be only to other objects of the same type (Same class or subclass)


Regards,
Vijay
 
Greenhorn
Posts: 19
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The type of a reference variable is always kept intact, reassigning it a different value doesn't change its type.
 
udaya krishna
Ranch Hand
Posts: 69
Netbeans IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot vijay and atul I understood clearly now
 
reply
    Bookmark Topic Watch Topic
  • New Topic