UpCasting and DownCasting
In object-oriented programming (OOP), upcasting and downcasting refer to the process of converting an object of a subclass to an object of a superclass and vice versa. To understand this concept, let's use an example of a mobile phone.
Consider the following class hierarchy for mobile phones:
In this hierarchy, SmartPhone extends the Phone class. The Phone class has a method makeCall, while SmartPhone has an overridden version of makeCall and an additional method surfInternet.
Upcasting:
Upcasting is a process of casting a subclass object into a superclass object. It is an implicit casting process, which means it is performed automatically by the Java compiler. Upcasting is generally used when we want to access the members of the superclass from a subclass object.
For example, consider the following code:
In the above example, we create a new SmartPhone object and upcast it to a Phone object. We can then call the makeCall method on the Phone object, which calls the overridden method of the SmartPhone class and prints "Making a call using internet" to the console.
Downcasting:
Downcasting is a process of casting a superclass object into a subclass object. It is an explicit casting process, which means it has to be performed manually by the programmer.
For example, consider the following code:
In the above example, we create a new SmartPhone object and upcast it to a Phone object. We then check if the Phone object is an instance of the SmartPhone class. If it is, we downcast the Phone object to a SmartPhone object and call the surfInternet method on it, which prints "Surfing the internet" to the console.
It is important to note that downcasting can only be done if the original object was upcasted from the subclass. If an object was not upcasted from the subclass, attempting to downcast it will result in a ClassCastException.
No comments:
Post a Comment