Examveda
Examveda

What will be the result of compiling and running the given code?
class A{
      int b=10;
      private A(){
            this.b=7;
      }
      int f(){
            return b;
      }
}
class B extends A{
      int b;
}
public class Test{
      public static void main(String[] args){
            A a = new B();
            System.out.println(a.f());
      }
}

A. Compilation Fails

B. Prints 0

C. Prints 10

D. Prints 7

E. None of these

Answer: Option A

Solution(By Examveda Team)

Choice A is the correct answer.

The code does not compile because the constructor of class A is declared as private. This creates a problem when the subclass constructor makes an implicit super() call to the parent class constructor at the time B is instantiated.

Since the code does not compile, all the other choices are incorrect. If the constructor of A had not been private, the output would have been 7.


This Question Belongs to Java Program >> Inheritence

Join The Discussion

Related Questions on Inheritence

What is inheritance in Java?

A. The process of acquiring properties and behaviors of one class by another

B. The process of creating objects

C. The process of encapsulation

D. The process of overloading methods