Given the following two classes:

public class Parent {
    protected int i;

    public Parent() {
        i = 1;
    }
}

public class Child extends Parent {
    private int i;

    public Child() {
        this.i = ((Child)new Parent()).getI();
        this.i = this.i++ + ++super.i;
    }

    public int getI() {
        return i;
    }
}
What will be the output of the following code?

public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        System.out.println(c.getI());
    }
}
Explanation
Unless you are dealing with a reference variable of a PARENT type pointing to an object of CHILD type - a superclass object cannot be cast to a subclass.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести