File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

assigning up the hierarchy

Mathew Lee
Ranch Hand

Joined: Jun 08, 2009
Posts: 238
I was reading following lines from link

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

Joined: Sep 28, 2004
Posts: 20516

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


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: 15081

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
I agree. Here's the link:
subject: assigning up the hierarchy
jQuery in Action, 3rd edition