+ 1
What happens in this statement ? " Superclass obj=new Subclass(); "
how can this be used in method override?
5 Respuestas
+ 2
Tomer Sim Waseem actually it wont throw an error
https://code.sololearn.com/czpxIsC112Si/?ref=app
i cant say for sure why this works but i think that the java compiler implicitly casts the superclass to the subclass, though that may not be exactly what it does, Danijel Ivanović Chriptus13 could you two elaborate on this because i am rather curious myself what exactly happens?
+ 2
So the SuperClass is Animal and SubClass is Cat therefore when you affect an Animal type variable with an instance of Cat it works because a Cat is always an Animal this is called inheritance! Plus im overriding the method test! and therefore it will be a polymorphic call to the method test, this means that besides that variable being the type Animal inside its a Cat and therefore it will make a call for the test method from Cat!
https://code.sololearn.com/c3IFHo6cVtD1/?ref=app
+ 1
Chriptus13 thank you for providing a more succinct explanation :)
+ 1
Robert Atkins np xD
0
this will cause an error..