java - Acceptable use of instanceof -
this question has answer here:
- is acceptable use of instanceof? 2 answers
i'm new java , struggling design problem. know use of instanceof
may indicate design flaw , understand given animal/dog/cat
classes example, replacing bark()
, meow()
makenoise()
etc.
my question is, sensible design if need call methods not have corresponding method depending on type of subclass? example, if want call new method biteleash()
if class dog
nothing @ if it's cat
?
i did consider having biteleash()
in animal
nothing, , overriding in dog
, there methods many seems clunky solution. in similar vein, if caller needs different depending on subclass has hold of, eg. terminate if subclass cat
? instanceof
acceptable here, or there better way?
public class animal { string name; public animal(string name) { this.name = name; } public string getname() { return name; } public void makenoise() { system.out.println("some noise generic animal!"); } } public class cat extends animal { public cat(string name) { super(name); } @override public void makenoise() { system.out.println("meow"); } } public class dog extends animal { public dog(string name) { super(name); } @override public void makenoise() { system.out.println("woof"); } public void biteleash() { system.out.println("leash snapped!"); } } import java.util.random; public class codeexample { public static void main(string[] args) { animal animal = getsomeanimal(); system.out.println("my pet called " + animal.getname()); animal.makenoise(); if (animal instanceof dog) { dog dog = (dog) animal; dog.biteleash(); // lots of other things because animal dog // eg. sign puppy training lessons } } private static animal getsomeanimal() { animal animal; random randomgenerator = new random(); int randomint = randomgenerator.nextint(100); if (randomint < 50) { animal = new dog("rover"); } else { animal = new cat("tiddles"); } return animal; } }
composition here, , idiomatic in java.
design interface called, say, leashable
. implemented dog
, not cat
.
rather using instanceof
, can attempt reference cast leashable
see if it's implemented particular object.
in opinion, should continue in similar vein: build noisyanimal
interface too. perhaps noisy
why should noisiness pertinent animals? implementing parrot
, say, have technical challenges beyond cat
or dog
. maintainable programs isolate areas of complexity , composition helps achieve that.
Comments
Post a Comment