Going over java inheritence, and can somone explain to me why both of these are
ID: 3889990 • Letter: G
Question
Going over java inheritence, and can somone explain to me why both of these are illegal. Drawing digrams helps too
List<Pets> pet = new LinkedList<Pets>;
List<Dog> dog = new LinkedList<Dog>;
List<Cat> cat = new LinkedList<Cat>;
pet.add(new dog); //Would the compiler accept the type of the parameter in the method call?
Pet[] pets = new Pet10];
Dog[] dogs = new Dog[10];
Cat[] cats = new Cat[10];
Pets[4] = new Cat();
Would the fourth statement be a legal assignment? Explain your answer.
Explanation / Answer
So, here I assume that both Dog and Cat are subclasses of the Pet Class
class Pet {
}
class Cat extends Pet {
}
class Dog extends Pet {
}
//Given Snippet
List<Pet> pet = new LinkedList<Pet>();
List<Cat> cats = new LinkedList<Cat>();
List<Dog> dogs = new LinkedList<Dog>();
pet.add(new Dog());
//Would the compiler accept the type of the parameter in the method call?
ans) Yes , the compiler will accept this type of parameter in the method call. pet list is of the type Pet, but we are trying to add Dog which is subclass of Pet, which is a valid scenario. You can pass subclass object whenever a superclass object is expected
Pet[] pet = new Pet[0];
Dog[] dog = new Dog[10];
Cat[] cat = new Cat[10];
pet[4] = new Cat();
//ans) Here also , Cat is subclass of Pet class. So, we are trying to assign Cat object to pet variable. We can assign subclass object to super class variable. So, this is valid. This concept is known as dynamic polymorphism
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.