I have Parent class X, and Parent class H.
H has in its field data a reference to a type X.
H’s constructor requires an instance of type X, which is then stored in the reference.
I then derive from X a Child class x1, and from H a child class h1.
h1 will accept in its constructor an instance of X or of x1.
But the methods and properties of x1 which are not already defined in its parent class X will not be available to h1.
How can I permanently cast x1 to the type of x1 within my class h1?
There is no such thing as a “permanent” cast (or, rather, the idea of a “permanent cast” is nonsensical, as that implies that casting does something to the object, which it does not, so there is nothing to either persist or undo). Your variable is of type
H, and the type of the variable will never change. Your instance is of typeH1, and the instance’s type will never change. Casting simply tells the compiler “Yes, even though I am only referencing this instance as typeH, I actually know that it is of typeH1, so it’s safe to store it in any variable that can reference an instance ofH1.”If your structure looks like this:
Then you’re going to have to store the value for the
h1variable somewhere else if you always want to use that value without downcasting.Now, a somewhat “smelly” way of accomplishing what you want (not having to write the casting code every time), you could do this:
This would allow you to refer to the same property named
HValueanywhere you had a reference toX1in a variable of typeX1. So…