Now, let's see how we are going to understand it in terms of upcasting. Sport, in common, is a parent object and each of its different forms is its child object and they have an IS-A relationship. So, it's correct to say that Cricket is-a sport or Football is-a sport (IS-A relationship). It's a personal choice to be interested in one sport or the other, be it cricket, football, hockey, etc. The reason is that the child object created here can show the properties of its parent, therefore it's correct to put the reference of its parent. Notice in this image that the reference variable is of the type Parent whereas the object is created of the type Child. Upcasting, in simpler words, is the typecasting of a child object to a parent object. Let's understand the meaning and differences related to upcasting and downcasting in Java. The purpose of typecasting is to enable a function in a program to process the variables correctly. Here, we're going to see how the conversion of an object takes place (because we have usually seen the typecasting in the case of datatypes only).īasically, we'll be typecasting an object to a data type and there would be a parent and child object for it. Typecasting is one of the important concepts in Java where the conversion of data types can be used for various purposes. ![]() Upcasting and downcasting in Java are the two forms of typecasting where conversion of data type takes place. Downcasting (or narrowing) is typecasting from a superclass to a subclass so that we can access the methods of the subclass, i.e., the child class. In this way, we can access the properties (methods and variables) of the superclass, i.e., the Parent as well. Upcasting (or widening) is the typecasting from a subclass to a superclass ( Child to Parent class). What is Upcasting and Downcasting in Java?
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |