Analyze the following code. import java.awt.*; import javax.swing.*; public class Test extends JFrame { public Test() { add(new MyDrawing("Welcome to Java!")); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class MyDrawing extends JPanel { String message; public MyDrawing(String message) { this.message = message; } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, 20 ,20); } }

Analyze the following code.
import java.awt.*;
import javax.swing.*;
public class Test extends JFrame  {
  public Test() {
    add(new MyDrawing("Welcome to Java!"));
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setSize(300, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}
class MyDrawing extends JPanel {
  String message;
  public MyDrawing(String message) {
    this.message = message;
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString(message, 20 ,20);
  }
}


A. The program runs fine and displays Welcome to Java!
B. The program would display Welcome to Java! if new JFrame() is replaced by Test().
C. The program would display Welcome to Java! if new JFrame() is replaced by new Test().
D. The program would display Welcome to Java! if new JFrame() is replaced by new Test("My Frame").

The correct answer is C

Explanation: (A) is incorrect because the constructor of Test is not invoked. (B) is incorrect because of the compile error on Test(). (C) is correct. (D) is incorrect because the Test class does not have a constructor with a String argument.


Java

Learn More Multiple Choice Question :