aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting " Watch "Casting " New topic
Author

Casting

komal sutaria
Greenhorn

Joined: Mar 26, 2007
Posts: 10
Hi!
everyone,

Here is the question:

class Parent{

}

public class Child extends parent{

public static void main(){

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



}

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
Komal
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
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: 1707
Hi,

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,
cmbhatt


cmbhatt
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting