-3

I have found this issue and I do not understand why constructors are being inherited in the first case. As far as I know, constructors are not inherited. Am I missing something very important ?

class Bird {
{ System.out.print("b1 ");}
public Bird() {System.out.print("b2 ");}

class Raptor extends Bird
{
    static {System.out.print("r1 ");}

    public Raptor() {System.out.print("r2 ");}

    {
        { System.out.print("r3 ");}
        static {System.out.print("r4 ");}
    }

class Hawk extends Raptor 
{    
    public static void main(String[] args)
    {    
        System.out.print("pre ");
        new Hawk();
        System.out.println("hawk ");
    }
}

The answer for the above is:

r1 r4 pre b1 b2 r3 r2 hawk

Mahbub Rahman
  • 1,295
  • 1
  • 24
  • 44
sri
  • 21
  • 1

1 Answers1

1

If you don't explicitly call the parent class constructor (via super(...)) or another constructor from the same class (via this(...)), the 0-argument parent class constructor is implicitly called.

Specifically, your code public Raptor() {System.out.print("r2 ");} implicitly calls the Bird constructor as the first thing, as if you had typed public Raptor() {super(); System.out.print("r2 ");}

Works similarly for your Hawk subclass.

Krease
  • 15,805
  • 8
  • 54
  • 86