DEV Community

Ildarov
Ildarov

Posted on • Edited on

Java Inheritance Puzzle

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

And then we execute this piece of code

SuperType superType = new ChildOfSuperType();
DefaultSuperType defaultSuperType = (DefaultSuperType) superType;
defaultSuperType.test()
Enter fullscreen mode Exit fullscreen mode

Do you know what will be printed?

Top comments (6)

Collapse
 
samwho profile image
Sam Rose

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 on ChildOfSuperType.

/me goes to check.

Spoiler here for anyone wondering what the answer is: repl.it/@samwho/KnownEnormousWeara...

Collapse
 
jrtibbetts profile image
Jason R Tibbetts

1. It doesn't matter whether superType is cast as DefaultSuperType, because it's still a ChildOfSuperType, and the function dispatch table will still point to ChildOfSuperType.test().

Collapse
 
nektro profile image
Meghan (she/her)

The others were right in saying "1", but you also have the annotation wrong. It's just @Override

Collapse
 
devit951 profile image
Ildarov

Thank you. I corrected it.

Collapse
 
anandu-str profile image
Ananthu

Despite the variable defaultSuperType being of type DefaultSuperType, it refers to an object of type ChildOfSuperType. Therefore, when test() is called on defaultSuperType, it invokes the overridden version of test() in ChildOfSuperType, resulting in 1

Collapse
 
mandraketech profile image
Navneet Karnani

"1". Because, in Java, the actual object's implementation is used, and not the typecast.