• Post Reply Bookmark Topic Watch Topic
  • New Topic

object oreintation  RSS feed

 
Aafreen Moinuddin
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
given the following program

interface I1 {} interface I2 {}
class Base implements I1 {}
class Sub extends Base implements I2 {}
class Orange {
public static void main(String args[]) {
Base base = new Base();
I1 i1 = base; // 1
Sub sub = (Sub)base; // 2

}}

its true that at line 2 it gives an run time error because because a super class cannot be assigned to sub class However it also true that a super class can be assigned to a sub class through an explicit cast (downcasting) which is done here in this case at line 2 .. so why does it still gives an error during runtime?


Can anyone answer ? please?
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A reference of a subclass can *not* reference an object of a superclass. You cannot assign an instance of java.lang.Object to a reference of type String, because you - for example - you cannot send Object the substring message.

*But* a reference of type Object *can* reference a String object. That doesn't lead to problems, because String understands every message that Object understands.

Now you could have a reference of type Object of which you simply *know* that it actually holds a String object, so you want to use it as a String. But the compiler doesn't know that it holds a String object, so you have to tell it - by using a cast. And if you are wrong, you will get an exception at runtime.
 
Aafreen Moinuddin
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but in the above case cast operator had already been given so that the compiler is told that sub is a object of Base
[ March 04, 2006: Message edited by: Aafreen Moinuddin ]
 
Joni Salonen
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

a reference provides a "window" to an object. It lets you see and use some parts of it, possibly leaving some parts hidden.

When you cast a reference, what you are changing is your view to the object. Not the object itself.

Now, the object behind your variable is of the type Base. With that cast you are asking to get a view of that object that would allow you to see and use things are specific to objects of class Sub, but the object doesn't have them! So changing the view doesn't make sense, and can't be allowed.

This article has a detailed explanation, please read it:
http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph-p2.html
 
Aafreen Moinuddin
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot joni!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!