• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Knute Snortum
  • Paul Clapham
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Frits Walraven
Bartenders:
  • Ganesh Patekar
  • Tim Holloway
  • salvin francis

assigning up the hierarchy  RSS feed

 
Ranch Hand
Posts: 238
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was reading following lines from link
http://www.jchq.net/certkey/0501certkey.htm

did not understand it clearly.

Object references can be assigned up the hierarchy from child to base.



The following example illustrates how you can cast an object reference up the hierarchy

class Base{}

public class ObRef extends Base{
public static void main(String argv[]){
ObRef o = new ObRef();
Base b = new Base();
b=o;//This will compile OK
/*o=b; This would cause an error indicating
an explicit cast is needed to cast Base
to ObRef */

}
}




I did not understand why b=o is ok where as o=b is not ok without casting.
Any ideas, resources,sample code,links, highly appreciated. thanks in advance.
 
author
Posts: 23832
140
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

After posting so many topics, mostly with some code snippets, you really should consider using code tags -- it makes your post much more readable.

Henry
 
Java Cowboy
Posts: 16084
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Mathew Lee wrote:I did not understand why b=o is ok where as o=b is not ok without casting.


Because that's how inheritance works in object oriented programming.

When class A extends class B, then there is an "is a" relationship going from B to A: an instance of B is an instance of A. This will become more clear when you fill in concrete names for the classes:

Study this tutorial: Object Oriented Programming Concepts.
 
WARNING! Do not activate jet boots indoors or you will see a tiny ad:
how do I do my own kindle-like thing - without amazon
https://coderanch.com/t/711421/engineering/kindle-amazon
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!