The Artima Developer Community
Sponsored Link

Java Answers Forum
Upcasting & Downcasting !

1 reply on 1 page. Most recent reply: Jul 16, 2003 7:50 AM by Boris Pruessmann

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Jaideep

Posts: 1
Nickname: djai
Registered: Jul, 2003

Upcasting & Downcasting ! Posted: Jul 14, 2003 11:39 PM
Reply to this message Reply
Advertisement
All,
Can someone let me know how things go inside the JVM when we try to do the following:

class parent {
int x;
public void m() {.../}
}
class child extends parent {
int x;
int y;
public void m() {../} //overiding
}

Now when we assign :
Parent po = new Parent();
Child co = new Child();
po = co;
po.x; // The value of x in parent class is called. Why ???
po.m; // The m in child is called. Why ???

co = po; // Can't Do why ???

Assumming that the JVM is implemeted as a heap with handle pool & object pool. Is it not that when we do po = co Or co = po , we are merely changing the object reference to point to other ?? Thanks in advance.

Jaideep.


Boris Pruessmann

Posts: 2
Nickname: docbobo
Registered: Jul, 2003

Re: Upcasting & Downcasting ! Posted: Jul 16, 2003 7:50 AM
Reply to this message Reply
> po.x; // The value of x in parent class is called. Why???

Polymorphism doesn't work for variables because late-binding is not possible. The decision which variable to access is based on the compile-time informat and that says: "this is of type Parent"

> po.m; // The m in child is called. Why ???

Here, polymorphism is working because you're calling a method. Decision which method to call is left to the VM which decides at runtime, based on the run-time type of the object stored in the variable.

> co = po; // Can't Do why ???

The compiler can only check information that is available at compile-time and that indicates that po is of type parent (which is not a child). The compiler will therefor refuse this line of code. Instead you have to do 'co = (Child) po', telling the compiler: "I know that po will be of type Child". However, there is the risk that po isn't a child at runtime and this'll result in a ClassCastException.

-Boris

Flat View: This topic has 1 reply on 1 page
Topic: Past Java Exam Question - help needed! please! Previous Topic   Next Topic Topic: jawin

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use