+ 1

What happens in this statement ? " Superclass obj=new Subclass(); "

how can this be used in method override?

8th Aug 2018, 11:34 AM
Waseem
5 Respostas
+ 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?
8th Aug 2018, 4:08 PM
StealthyTaco
StealthyTaco - avatar
+ 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
8th Aug 2018, 9:58 PM
Chriptus13
Chriptus13 - avatar
+ 1
Chriptus13 thank you for providing a more succinct explanation :)
9th Aug 2018, 10:21 AM
StealthyTaco
StealthyTaco - avatar
+ 1
9th Aug 2018, 10:24 PM
Chriptus13
Chriptus13 - avatar
0
this will cause an error..
8th Aug 2018, 2:40 PM
Tomer Sim
Tomer Sim - avatar