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

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes