Java Programming - Java.lang Class - Discussion


What will be the output of the program?

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

[A]. It compiles and runs printing nothing
[B]. Compiles but fails at runtime
[C]. Compile Error
[D]. Prints "complete"

Answer: Option C


No constructor has been defined for class B therefore it will make a call to the default constructor but since class B extends class A it will also call the Super() default constructor.

Since a constructor has been defined in class A java will no longer supply a default constructor for class A therefore when class B calls class A's default constructor it will result in a compile error.

Nilesh said: (Jun 22, 2014)  
Default constructor of class B gives calls to constructor of class A. So output is complete.

Please friends this is correct or not ?

Please help me.

Ankit Tyagi said: (Jun 24, 2014)  
Read these points carefully and then approach the problem statement:

1. The default constructor invokes the no-arg constructor of the superclass.

2. The compiler creates a default constructor only when there are no other constructors for the class.

Now since class A has a user defined constructor with an integer argument already, the compiler will not make a default constructor and since there is no default constructor the call made from Class B to class A's default constructor will not resolve and therefore there will be a compilation error. I hope this solves your doubt.

Mukesh Singh said: (Nov 14, 2017)  
Yes of course in parent child hierarchy compiler looks for a method from child to parent class. If it will not be there till traversing whole hierarchy then it will give compile error. But what about the rule that if no constructor is there then a default will be there?

Sushma said: (Apr 24, 2022)  

Anyone, explain the flow of the program

public class A {
public void test() {

public class B extends A {
public void test1() {

public static void main(String[] args) {
B b1=new B();

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.