What will be printed?

class ClassA {
    int x = 1;

    public void printX() {
        System.out.println(getX());
    }

    public int getX() {
     return x;
    }
}

class ClassB extends ClassA {
    int x = 2;

    public int getX() {
        return x + 1;
    }
}

public class Test {
    public static void main(String[] args) {
        ClassA a = new ClassB();
        System.out.println(a.x);
    }
    }
Explanation
The correct answer is 1. Since the type of variable is the class ClassA, the variables of this class hides the variables of the class ClassB when calling this variable through the reference with the type of ClassA

Следи за CodeGalaxy

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

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