DEV Community
Imagine we have one interface and these classes:
interface SuperType {
void test();
}
class DefaultSuperType implements SuperType{
@Override
void test(){
System.out.println("0")
}
}
class ChildOfSuperType extends DefaultSuperType{
@Override
void test(){
System.out.println("1")
}
}
And then we execute this piece of code
SuperType superType = new ChildOfSuperType();
DefaultSuperType defaultSuperType = (DefaultSuperType) superType;
defaultSuperType.test()
Do you know what will be printed?

Excellent Blog very imperative good content
Core Java Training in KPHB
Top comments (7)
I think it's 1, and it's because the object is always of type
ChildOfSuperType
no matter what type you store it in, so when the method is dispatched it will always resolve to the version onChildOfSuperType
./me goes to check.
Spoiler here for anyone wondering what the answer is: repl.it/@samwho/KnownEnormousWeara...
1
. It doesn't matter whethersuperType
is cast asDefaultSuperType
, because it's still aChildOfSuperType
, and the function dispatch table will still point toChildOfSuperType.test()
.The others were right in saying
"1"
, but you also have the annotation wrong. It's just @OverrideThank you. I corrected it.