Java Programming - Java.lang Class - Discussion

Discussion Forum : Java.lang Class - Finding the output (Q.No. 9)
9.
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(); 
        System.out.println("complete"); 
    } 
}
It compiles and runs printing nothing
Compiles but fails at runtime
Compile Error
Prints "complete"
Answer: Option
Explanation:

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.

Discussion:
4 comments Page 1 of 1.

Sushma said:   3 years ago
@All.

Anyone, explain the flow of the program



public class A {
A(){
System.out.println(100);
}
public void test() {

System.out.println(122);
}
}
public class B extends A {
public void test1() {

super.test();
}
public static void main(String[] args) {
B b1=new B();
b1.test1();
}
}

Mukesh Singh said:   8 years ago
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?
(2)

Ankit Tyagi said:   1 decade ago
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.

Nilesh said:   1 decade ago
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.

Post your comments here:

Your comments will be displayed after verification.