Multiple choice technology programming languages

Following code will result in: class A { public static void main(String [] args) {A a = new B(); }} class B extends A {}

  1. Compiler error

  2. Runtime Exception

  3. No errors

  4. Runtime Error

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

Class B extends Class A, making B a subclass of A. In Java, assigning an instance of B to a reference variable of type A (A a = new B()) is a valid polymorphic upcast. This code compiles successfully and executes without generating any runtime exceptions or errors.

AI explanation

To answer this question, let's analyze the given code:

class A {
    public static void main(String[] args) {
        A a = new B();
    }
}

class B extends A {}

In the code, a class A is defined with a main method. Inside the main method, an object a of type A is created using the constructor of class B. Class B is a subclass of A.

Since class B extends class A, it is considered to be a subtype of A. Therefore, it is valid to assign an instance of B to a variable of type A. This is known as polymorphism in Java.

Hence, there are no errors in the given code, and the correct answer is C) No errors.