title: Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly?
body: <p>I have a question about inheritance in Java.</p>
  
  <p>I have two classes <code>A</code> and <code>B</code> , and class B, <strong>inherits</strong> from A:</p>
  
  <pre><code>public class A {
       public A() {
           System.out.println("Hi!");
       }
  }
  
  
  public class B extends A {
       public B() {
           System.out.println("Bye!");
       }
  
       public static void main(String[] args) {
           B b = new B();
       }
  }
  </code></pre>
  
  <p>When I run program B, the output is:</p>
  
  <pre><code>Hi!
  Bye!
  </code></pre>
  
  <blockquote>
    <p><strong>Question</strong> : why the <strong>constructor</strong> of <code>class A</code> is invoked, when I create and object of <code>class B</code> ? </p>
  </blockquote>
  
  <p>I know that B inherits everything from A - all instance or class variables, and all methods, and in this sense an object of B has all characteristics of A plus some other characteristics defined in B. However, I didn't know and didn't imagine that when I create an object of type B, the constructor of A is also invoked.
  So, writing this:</p>
  
  <pre><code>B b = new B();
  </code></pre>
  
  <p>creates <strong>Two objects - one of type B, and one of type A</strong>.</p>
  
  <p>This is getting interesting, </p>
  
  <p>can somebody explain why exactly this happens?   </p>