Java - Interview Questions and Answers on Inheritance and Composition

Q1.  Does Java support Multiple Inheritance ?

Ans. Interfaces does't facilitate inheritance and hence implementation of multiple interfaces doesn't make multiple inheritance. Java doesn't support multiple inheritance.

Q2.  Why java doesn't support multiple Inheritence ?

Ans. class A {
      void test() {
          System.out.println("test() method");
      }
}

class B {
         void test() {
            System.out.println("test() method");
         }
}

Suppose if Java allows multiple inheritance like this,

class C extends A, B {
}

A and B test() methods are inheriting to C class.

So which test() method C class will take? As A & B class test() methods are different , So here we would Facing Ambiguity.

Q3.  Are constructors inherited? Can a subclass call the parent's class constructor? When?

Ans. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to override the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.

Q4.  Can we reduce the visibility of the inherited or overridden method ?

Ans. No.

Q5.  Which of the following is tightly bound ? Inheritance or Composition ?

Ans. Inheritence.

Q6.  Does a class inherit the constructor of its super class?

Ans. No.

Q7.  Difference between Compositions and Inheritance ?

Ans. Inheritance means a object inheriting reusable properties of the base class. Compositions means that an abject holds other objects.

In Inheritance there is only one object in memory ( derived object ) whereas in Composition , parent object holds references of all composed objects.

From Design perspective - Inheritance is "is a" relationship among objects whereas Composition is "has a" relationship among objects.

Q8.  Can we compose the Parent Class object like this ?

class BuggyBread1 extends BuggyBread2 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
buggybread2 = new BuggyBread2();
}
}

Ans. Yes.

Q9.  What are the difference between composition and inheritance in Java?

Ans. Composition - has-a relationship between objects.
Inheritance - is-a relationship between classes.

Composition - Composing object holds a reference to composing classes and hence relationship is loosely bound.
Inheritance - Derived object carries the base class definition in itself and hence its tightly bound.

Composition - Used in Dependency Injection
Inheritance - Used in Runtime Polymorphism

Composition - Single class objects can be composed within multiple classes.
Inheritance - Single class can only inherit 1 Class.

Composition - Its the relationship between objects.
Inheritance - Its the relationship between classes.