I read a really good post about up and downcasting on this forum:
http://forum.codecal...owncasting.html
But my question is, why do you want to cast?
(referring to the link I posted up there)
if all cats can perform animal methods, why would you want to upcast a cat to an animal in first place?
p.s: wasn't sure where to post...
2 replies to this topic
#1
Posted 15 May 2011 - 05:32 PM
|
|
|
#2
Posted 15 May 2011 - 08:56 PM
Found a really good tutorial on this. I don't know this so I'm currently reading it.
http://forum.codecal...owncasting.html
http://forum.codecal...owncasting.html
#3
Posted 16 May 2011 - 03:24 AM
You want to cast because you will have to write less code. Take the example of Cat and Dog who extend Animal. Now you have another class Cage (how cruel ^^). Cage can hold both dog and cat. Without casting your Cage class will look like:
Also with generics, like an ArrayList, you can't put a Dog AND a cat in an ArrayList.
public class Cage{
private Cat cat;
private Dog dog;
public void addCat(Cat cat){
this.cat = cat;
}
public void addDog(Dog dog){
this.dog = dog;
}
}
While with casting you can just dopublic class Cage{
private Animal animal;
public void addAnimal(Animal animal){
this.animal = animal;
}
}
Also with generics, like an ArrayList, you can't put a Dog AND a cat in an ArrayList.
ArrayList<Dog, Cat> myPets = new ArrayList<>(); //Won't workThat's not possible. You can however decide to put Animal in the arrayList, and then both dog and cat can be added:
ArrayList<Animal> myPets = new ArrayList<>(); myPets.add(new Cat()); myPets.add(new Dog()); ... Cat cat = (Cat) myPets.get(0); Dog dog = (Dog) myPets.get(1);
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account

Back to top









