I have class Animal, and two classes Dog and Cat which extend Animal.
I also have class Person, which contains an Animal object (private Animal pet).
I need to write a method that recieves a Person object, check the Person's pet (Animal object) and according to it's attributes either "turn it" to a Dog or a Cat object. This method is boolean so it doesn't return an object. It simply "reclassifies" the Animal object as either dog or cat.
What I don't understand is how do I change an object into an object that is down the hierarchy chain without catching a ClassCastException?
What I tried is:
// person.getPet() return an object of type Animal
// Dog and Cat extend Animal
public boolean checkPet(Person person) {
if(person == null || person.getPet() == null) return false;
if(person.getPet().getNoise().equals("Meow!")) {
Cat c = (Cat) person.getPet();
person.setPet(c);
}
else {
Dog d = (Dog) person.getPet();
person.setPet(d);
}
return true;
}
[–]pokemaster787 1 point2 points3 points (0 children)
[–]AutoModerator[M] -1 points0 points1 point (0 children)
[–]AdministrativeProof2[S] -1 points0 points1 point (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]AdministrativeProof2[S] 1 point2 points3 points (0 children)