File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting " Watch "Casting " New topic


komal sutaria

Joined: Mar 26, 2007
Posts: 10

Here is the question:

class Parent{


public class Child extends parent{

public static void main(){

Child child = new child();
Parent p = child;


public void publicChild(){
System.out.println("public child class");

Here when we create a instance of class Child. JVM save object (instance of class Child ) into Heap and it's address assign to reference varaible child into stack.
when we create referece variable parent of Parent type and assign child reference (address of Child instance object) to parent referece variable.
parent reference variable actually able to access all the method of child class.but it's not and we need to downcast again ... why ?
can anyone explain why ?

Thanks in advance
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2398
A Parent reference can only see the methods defined in Parent, not methods that are only defined in Child.
[ March 28, 2007: Message edited by: Keith Lynn ]
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710

Using Parent class reference variable you can only access the methods of the child class, parent class is known of. In other words the Parent class only have information of the methods it is having so at run time if the Parent class reference variable holds reference of the Child class instance, polymorphism is achieved by calling child class methods using Parent class reference variable.

You do downcast in the case you have to access the Child class specific methods using Parent class reference but you may recall, you should do instanceof test before doing so to make yourself confirmed YEAH the Parent class reference refers to Child class. Here compiler relies on you to downcast, So be faithful, do instanceof test and then do downcast to access the Child class specific method.

Downcast is must because using Parent class reference you are only able to access Parent class methods polymorphically on the Child class object.

Did I miss something!

Thanks and Regards,

I agree. Here's the link:
subject: Casting
It's not a secret anymore!