![]() ![]() A method which prints the data of the parent class Here, the subclass object is referred by the parent class.īelow is an example of downcasting in which both the valid and the invalid scenarios are explained: ![]() Now the point is if downcasting is not possible in Java, then why is it allowed by the compiler? In Java, some scenarios allow us to perform downcasting. However, when we run it, it throws the "ClassCastException". In Java, we cannot assign a parent class reference object to the child class, but if we perform downcasting, we will not get any compile-time error. In Upcasting, we assign a parent class reference object to the child class. Upcasting is another type of object typecasting. Upcasting is also known as Generalization and Widening. We access only some specified variables and methods of the child class. Here, we don't access all the variables and the method. By using the Upcasting, we can easily access the variables and methods of the parent class to the child class. Upcasting is a type of object typecasting in which a child object is typecasted to a parent class object. Let's dive into deep of both these type of object casting: 1) Upcasting We can perform Upcasting implicitly or explicitly, but downcasting cannot be implicitly possible. In Upcasting and Downcasting, we typecast a child object to a parent object and a parent object to a child object simultaneously. Typecasting is used to ensure whether variables are correctly processed by a function or not. So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to Parent or can say Upcasting and Downcasting. Parent and Child objects are two types of objects. In Java, the object can also be typecasted like the datatypes. Next → ← prev Upcasting and Downcasting in JavaĪ process of converting one data type to another is known as Typecasting and Upcasting and Downcasting is the type of object typecasting. ![]()
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |