Jump to content

about casting/downcasting

- - - - -

  • Please log in to reply
2 replies to this topic

#1
John Jang

John Jang

    Newbie

  • Members
  • Pip
  • 1 posts
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
An Alien

An Alien

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 260 posts
Found a really good tutorial on this. I don't know this so I'm currently reading it.
http://forum.codecal...owncasting.html

#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
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:

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 do

public 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 work

That'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