So here I'm creating a Dog object w.rt Animal. Hence Dog extends Animal(is-a relationship), so we can use the base class(Super Class) methods in the derived class(Subclass)Ĭonsider the below piece of code in the Main Method now, If you look into the Animal and Dog class, each are having their own methods like getAnimalName() and getDogName(). The compile error can be removed by adding a cast but would anyway break at the runtime. By the way, downcasting is dangerous you can have this RuntimeException, if its for training purpose its ok. Animal a new Animal () // a points in heap to Animal object Dog dog (Dog)a // A dog is an animal but not all animals are dog. No cast is requiredĭowncasting - Conversion from parent to child - Explicit cast is required 202 Upcasting is allowed in Java, however downcasting gives a compile error. An animal could not be a dog can be a cat or something else like in your case an Animal. Upcasting - Conversion from child to parent - Compiler takes care. In our case, runtime class information gives power to the programmer because he or she has more information to work with. And I knew what is upcasting and downcasting. I Knew there are plenty of articles/questions in stackoverflow describing about upcasting and downcasting in Java. If, based on our knowledge of the code, we are sure that the object will always be of type MemorizingDeck, we can downcast the variable from a supertype.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |