I have parent/base class as below:
class Base {
...
}
Also, having the child class as below:
class Child: Base {
...
func someFunc() {
}
}
I have created the instances of Parent class as below:
let baseObj = Base()
Now, I want to call the method of Child class from the parent object. So I have code like below:
let childObj = baseObj as! Child
childObj.someFunc()
But this is giving me runtime crash like below:
Could not cast value of type 'PCTests.Base' (0x11c6ad150) to 'PCTests.Child' (0x11c6ab530).
However, we can forcefully cast a parent to a child which is known as downcasting. After we define this type of casting explicitly, the compiler checks in the background if this type of casting is possible or not. If it's not possible, the compiler throws a ClassCastException.
Downcasting is the opposite of upcasting, and it refers to casting an object of a parent class type to an object of its children class. Downcasting is used to reconvert objects of a children class that were upcasted earlier to generalize. Let's say you own two cars and three trucks.
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.
Following the object oriented methodology, a child class can be instantiated as an object that can inherit the attributes of the parent class. This is the process of inheritance, much like how a benefactor can pass on their wealth or assets to a beneficiary.
Error says it all.... You cannot typecast parent into child object. Thats not how inheritance works.
You can achieve that by making object of child class actually, and you should keep structure in that way as this is core concept of Base and child class, if you do following it should work:
let baseObj = Child()
Now in base class you can do following
let childObj = self as! Child
childObj.someFunc()
Whereas someFunc
is defined in child class.
P.S. Would be my pleasure to clarify if it doesn't make sense for you, thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With