wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Downcasting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Downcasting" Watch "Downcasting" New topic
Author

Downcasting

Satyajeet Kadam
Ranch Hand

Joined: Oct 19, 2006
Posts: 215
Q1) Is it necessary to use instanceof operator before downcasting ?
any aletrenatives?

Q2)
<code>
package coreservlets;

/**
*
* @author satya
*/
class Animal
{
public void Test(){
System.out.println("In Animal");
}
}

class Dog extends Animal
{

public void test(){
System.out.println("In Dog cl;ass");}
}

public class Dogtest
{

public static void main(String args[])
{

// Animal obj =new Animal();
Animal obj=new Dog();
if( obj instanceof Dog)
{

System.out.println("Animal is a dog"); // line 1
Dog ref=(Dog)obj;
ref.Test();// line 2

}

else
{

System.out.println("Animal is not a dog");

}
}
}

</code>


output:
init:
deps-jar:
compile-single:
run-single:
Animal is a dog
In Animal
BUILD SUCCESSFUL (total time: 0 seconds)



Q3)why it has calling parent class method? it supposed to call overidden method
Alex Belisle Turcot
Ranch Hand

Joined: Apr 26, 2005
Posts: 516
Hi,

Originally posted by amolpalekar kadolkar:

Q3)why it has calling parent class method? it supposed to call overidden method


For Q3, it's because you didn't use the same method name, one is "test" and the other is "Test".

Alex
Alex Belisle Turcot
Ranch Hand

Joined: Apr 26, 2005
Posts: 516
Originally posted by amolpalekar kadolkar:
Q1) Is it necessary to use instanceof operator before downcasting ?
any aletrenatives?


Q1: Technically speaking, you don't need to use instanceOf, if you know you expect a certain type.

Take for example when you put Strings in an ArrayList. When you get the object later on, you know it's a String and you'll cast it to String right away (Assuming you're not using "Type-Safety".

If the object can be multiple different object, than, yes instanceOf is the choice. Unless, of course there's a specific value in your object that you can check if(obj.isDog() == true).

Technically speaking here.

Regards,
Alex
[ January 22, 2008: Message edited by: Alex Belisle Turcot ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Downcasting
 
Similar Threads
What is the difference between overriding a method and redefining a method ?
Whats wrong with this code
Confused with instanceof, please help
Please explain Downcasting issue
Reference Variable Casting