wood burning stoves*
The moose likes Beginning Java and the fly likes assigning up the hierarchy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "assigning up the hierarchy" Watch "assigning up the hierarchy" New topic
Author

assigning up the hierarchy

Mathew Lee
Ranch Hand

Joined: Jun 08, 2009
Posts: 238
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.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18874
    
  40


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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14193
    
  20

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
GeeCON Prague 2014
 
subject: assigning up the hierarchy