Tuesday, November 12, 2019

Java Coding Interview Questions-1

Q- What is output of the program?

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A(String name) {
  this.name = name;
 }

}

class B extends A {

}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 Implicit super constructor A() is undefined for default constructor. Must define an explicit constructor

 at corejavaExample.B.<init>(C.java:22)
 at corejavaExample.C.main(C.java:6)

This is because parent class has parameterized constructor but child class don't have constructor So how the parent class constructor would be initialized.
So if parent class has parameterized constructor than child class must have parameterized constructor.
                 Or
Parent class should have no-argument or default constructor  then child class may not have constructor is possiple.
Solution-1:

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B("Ram kumar");
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A(String name) {
  this.name = name;
 }

}

class B extends A {

 public B(String name) {
  super(name);
  // TODO Auto-generated constructor stub
 }

}
Output:

Ram kumar
Solution-2:

package corejavaExample;

public class C {

 public static void main(String[] args) {
  A b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A() {
  System.out.println("Hi");
 }
 
 public A(String name) {
  this.name = name;
 }

}

class B extends A {

}

If parent class don't has parameterized constructor then constructor is Optional in child class (i.e. not required). clear from below example.

package corejavaExample;

public class C {

 public static void main(String[] args) {
  B b = new B();
  System.out.println(b.name);
 }

}

class A {

 public String name;

 public A() {
  System.out.println("Hi");
 }

}

class B extends A {

}
Output:

Hi
null

No comments:

Post a Comment