It is often the ease that two or more classes share a common set of methods. For
ID: 3814988 • Letter: I
Question
It is often the ease that two or more classes share a common set of methods. For programming purpose we might wish to treat the objects of those classes in a similar way by invoking some of their common routines. For example, the Dog and Cat classes listed below agree on the method speak. Because Dog and Cat objects have the ability to "speak, " it is natural to think of putting both types of objects in an ArrayList and invoking speak on every object in the list. Is this possible? Certainly we could create an ArrayList of Dog that would hold all the Dog objects, but can we then add a Cat object to an ArrayList of Dog? Try running the main program below as it is written. Run it a second time after uncommenting the line that instantiates a Cat object and tries to add it to the ArrayList.Explanation / Answer
No, We can not add a Cat Object in the arraylist of of type Dog object.
We will be able to put Cat object in ArrayList of type Dog if Cat is child class of Dog.
TO Solve the above problem, we should create a Animal class and put all common methods in Animal class and make Dog class and Cat class to extends Animal class. THen create a ArrayList of type Animal and then we can put Dog as well as Cat Obejct in ArrayList
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.