java - Polymorphic arguments work with superclass but not with subclass -
this question has answer here:
i learning polymorphism easy on me (literally copying book). try pass class argument method. when can call superclass methods, not actual subclass. using start() method, try make wolf howl:
public class experiment { public static void main(string[] args) { petowner own = new petowner(); own.start(); } } //trying polymorphic arguments class vet { public void giveshot(animal a) { a.howl(); } } class petowner { public void start() { vet v = new vet(); wolf w = new wolf(); v.giveshot(w); } } //inheritance// //kingdom - animal class animal { public void move() { system.out.println("*motions softly*"); } } //family - canine class canine extends animal { public void bark() { system.out.println("woof!"); } } //species - wolf class wolf extends canine { public void howl() { system.out.println("howl! howl!"); } } if pass howl method superclass (animal) works fine. if call directly wolf class - works fine. instance doesn't work if try pass wolf class argument , call there.
here why try way, quoted head first java pg 187:
the vet's giveshot() method can take animal give it. long object in argument subclass of animal, work
i getting "cannot find symbol symbol: method howl(), location variable of type animal" error.
you're calling a.howl() while a instance of animal class. animal not know how howl. wolf does.
you can defin method react() , override particular subclass of animal;
Comments
Post a Comment