What will be printed?

class ClassA {
    int x = 1;

    public void printX() {

    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();
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
Java Quiz
Start Quiz

or Read more about Java Quiz

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback