inheritance - Initializing objects using a super class instead of the subclass -
i saw illustration code , didn't know how i'd able find reply question had. in code dog object, cow object , snake object declared animal objects. valid declare object using more generic class? instance, declare object object (since classes subclasses of object class)? advantages/disadvantages of declaring specific or more general? ease of readability?
class animal { void whoami() { system.out.println("i generic animal."); } } class dog extends animal { void whoami() { system.out.println("i dog."); } } class cow extends animal { void whoami() { system.out.println("i cow."); } } class snake extends animal { void whoami() { system.out.println("i snake."); } } class runtimepolymorphismdemo { public static void main(string[] args) { animal ref1 = new animal(); animal ref2 = new dog(); animal ref3 = new cow(); animal ref4 = new snake(); ref1.whoami(); ref2.whoami(); ref3.whoami(); ref4.whoami(); } } output generic animal. dog. cow. snake.
you instantiate every other class object, not primitives, though have wrappers create them classes.
it's not object oriented practice because want programme fail safe possible.
put more varied methods classes , that's when start see problems.
lets dog has method chewbutt().
animal dog = new dog(); dog.chewbutt();
no problem there. that's not you're allowed do.
animal dog = new cow();
that compiles...
dog.chewbutt();
now have problem. cow can't reach butt.
you want stringent possible when declaring superclass loose plenty job done fast. reason may want looser this.
dogs , snakes little different. i'mma create new subclass mammal extends animal. set dog , cow , whatever else in it.
now can assured can do:
mammal mouse = new mouse(); mouse.suckleyoung(); cat.suckleyoung(); whale.suckleyoung();
but if accidentally try:
mammal snake = new snake();
i want compiler complain before dig myself coding hole.
i hope helps. experience fire points brain enough.
object inheritance declaration
No comments:
Post a Comment