What will be displayed?

class A {
    int i = 0;
    public int increment() {
        return ++i;
    }
}
 
public class B extends A {
    int i = 10;
    public int increment() {
        return ++i;
    }
 
    public static void main(String[] args) {
        A obj = (A) new B(); 
        System.out.println(obj.increment());
    }
}
Explanation
Method A.increment() overlaps in class B.
Therefore, regardless of the type of the variable obj, will be called the method corresponding to the actual type of the object - that is, B.increment().
This method will use the variable i, declared in the same class B and having an initial value of 10.
The resulting value - 11.

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты