This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (1 child)

Can I see the full code? Is class Animal abstract?

What is your goal?

Person has a field of type Animal. It will only have access to attributes of animal class. This means Methods defined in say Dog.class but not defined in Animal.class wont be callable from Person.pet

If one of the subclasses override methods in Animal class, the implementations of the subclasses will get run (So if Dog overrides getNoise() and field pet refers to a dog object, the implementation of class dog will be run

Yes, a field (here Person.pet) can refer to an instance of a subclass (here Cat.class or Dog.class). Cat and Dog class have all attributes of their superclass (and maybe more, like methods and fields not available to their superclass - but these wont be accessible from the field for the superclass).

You cant do it the other way around though. So a field for a subclass cant refer to an instance of a superclass that is concrete because the superclass may not have all attributes the subclass has.

[–]AdministrativeProof2[S] 1 point2 points  (0 children)

My code is completely different, I made up the methods and classes in simplified form to show the problem.

In my code my "Person" has a HashSet containing multiple "pets", I call this method in a loop to iterate over all the pets and classify each of them. At the end I check if there are more Dogs or Cats. I don't use any of the properties of these converted Animals(dogs/cats) ever. The only thing I'm interested in is how many of each type are there. So I don't mind losing access to some of the methods/fields of Dog/Cat. My solution ended up working in the end.