I have a variable: Abstract a. It is a class that extends the Abstract class. However, I need to cast this Abstract variable into a more specific class variable that extends the Abstract class.
My situation: I have two classes, Class1 and Class2 that both extend the Abstract class with methods implemented in each one. I now have an Abstract class variable to work with. I do not know if it is Class1 or Class2, so I cannot simply do a (Class1) a or a (Class2) a (casting).
So how would I successfully cast this variable so that I can use the inner methods?
I was thinking along the lines of using a.getClass().getName() to determine how to cast it, but I am stuck from here on out.
Your new question appears to be asking how to dynamically cast a variable to an arbitrary type unknown at runtime. This is probably a duplicate of java: how can i do dynamic casting of a variable from one type to another? but to summarize, this is not (easily) possible, isn’t recommended, and speaks to other issues in your code.
Think about it this way, what variable would you possibly be able to use to store your newly cast object? Imagine if we had a
(child)cast operation in Java, that took a variable defined as a parent class, and cast it down to its child (e.g. List -> LinkedList):Notice that 1) there’s no way you could ever specify a type for
var, since we don’t know at runtime what type it will be; and 2) there’s nothing we’d be able to do with var beyond the behavior defined inAbstractanyways, because the compiler can’t predict which methods will be availible tovarother than what’s available toAbstract.If you need to implement class-specific behavior, you should do so inside the class. Have an abstract method which each class has to implement, and which can do whatever you need them to do. Or, if you cannot ensure that, don’t define a function that takes an
Abstractas an argument; instead define however many functions that takeClass1,Class2, etc. objects as parameters, like so:Abstract method to require all child classes behave similarly
Functions only for classes that can actually handle what you want
Again, if neither of these options are viable for you (and of course, blocks of
instanceofcalls aren’t acceptable) then I’d be willing to bet money there’s something structural in the way you’re using Java that’s fundamentally incorrect. If you want to post a code sample of exactly what you’re trying to accomplish by child-casting, perhaps we can shed some light as to what the issue is.Leaving this here for posterity – OP’s original question asked about creating new instances of an object cast as its abstract parent.
Pretty straightforward, get the object’s class object, and create a new instance. For more complex constructors, see the Java documentation on creating new instances dynamically.
Result: