Java OOPC - Casting

 

Casting

 

Casting is what assigning data types in hierarchical way. That means we cannot assign big type to small type data. If we said in a detailed way in we cannot assign first place data type in hierarchy to last data types in hierarchy.

 


 

Upcasting and Downcasting




 

 Two essential concepts in OOP are upcasting and downcasting, which involve the manipulation of object references and inheritance.

 

Upcasting

   Upcasting involves treating an object of a derived class as an object of its base class. In simpler terms, it's moving up the class hierarchy. This is inherently safe, as every instance of the derived class is also an instance of the base class. Consider the following example in Java,

 

Upcasting is the  process of assigning the object from sub class to the variable in the form of Super class reference.

Always object run from the class of the object created.so because of that the final propose of the upcasting is running the sub class.

Assigning child class object to parent class reference Is the simply idea of the upcasting.

 


 

 

   In this example, a `Dog` object is upcasted to an `Animal` reference. This is useful in scenarios where you want to use a generic reference to handle objects of multiple related classes.

 

Downcasting

Downcasting is the process convert again as the variable that object  assigned sub class   variable that in as  super class reference.

 

  It's on the other hand of upcasting, downcasting is the process of casting a reference of a base class to one of its derived classes.

In simply can tell downcasting is that assigning parent class reference (which is pointing to the child class object) to child class reference.




This operation is potentially unsafe, as not every base class object is an instance of the derived class.


Here below example consists upcasting and downcasting .It help you to understand what it means.




   Upcasting and downcasting are concepts in OOP that enable developers to work with class with inheritance.


Here is the comparison of two types of casting,




Comments

Popular posts from this blog

Linked List Data Structures

Java OOPC -Encapsulation

Java OOPC - Interface