Java Daily, Quiz 3

Welcome to Java daily quiz 3, test yourself with this Java quiz. The answer and explanation are given at the end for your reference.
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out 200+ video tutorials on my YouTube channel at https://www.youtube.com/c/javaguides.

Quiz 3 - What will be the output of the following Java program?

class Base {
    public void test() {
    }
}

class Base1 extends Base {
    public void test() {
         System.out.println("Base1");
    }
}

class Base2 extends Base {
    public void test() {
         System.out.println("Base2");
    }
}

class Test {
    public static void main(String[] args) {
        Base obj = new Base1();
        ((Base2) obj).test(); // CAST
    }
}
a) The program will print the following: Base1.
b) The program will print the following: Base2.
c) The compiler will report an error in the line marked with comment CAST.
d) The program will result in an exception (ClassCastException).

Answer

d) The program will result in an exception (ClassCastException).
Explanation: The dynamic type of variable obj is Base1 that you were trying to cast into Base2. This is not supported and so results in an exception.

I have executed this program in Eclipse IDE and find the below screenshot of the same for your reference:
Check out all the Java daily quiz questions at https://www.javaguides.net/p/java-daily-quiz.html.
Check out 200+ video tutorials on my YouTube channel at  https://www.youtube.com/c/javaguides

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments