• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Downcasting

 
Satyajeet Kadam
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 516
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic