Objects and casting java -


i given statement homework.

mammal pet = new dog ();

samoyed s = pet;

we given diagram so:

animal ---> vertebrate ---> mammal ---> dog ---> husky, samoyed, beagle

my understanding code isn't valid , cannot cast. mammal refers dog object , samoyed type not in dog or mammal.

is correct?

you can put child reference in parent object reverse not true. first statement valid dog child of mammal. second statement incorrect trying parent object of mammal child reference samoyed.

basically jvm uses concept of parent object hold child reference polymorphism. imagine scenario have design method can take input of kind of animal. can write testmethod(animal animal), method can accept object of type animal or childs(which animal because inherit). if feature not available end writing different methods different kind of animals.

hope helps!


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -