3 Replies Latest reply: Jan 14, 2011 6:50 PM by EJP RSS

    what is an empty constructor?

    820362
      Hi.
      This might be a dumb question but I need to know what is an empty constructor?
      I've checked my Murach and there is nothing mentioned.
      Thank you.
        • 1. Re: what is an empty constructor?
          796440
          It's a constructor with no code in its body.
          public class Foo {
          
            // empty
            public Foo() {
            }
          
            // empty
            public Foo(int x) {
            }
          
            // not empty
            public Foo(String s) {
              System.out.println(s);
            }
          }
          An empty constructor is equivalent to having a body that simply calls
          super();
          In fact, I'm pretty sure the compiler puts the bytecodes for a super(); call into your class file just as if you had explicitly written it in the constructor body.
          • 2. Re: what is an empty constructor?
            jschellSomeoneStoleMyAlias
            jverd wrote:
            In fact, I'm pretty sure the compiler puts the bytecodes for a super(); call into your class file just as if you had explicitly written it in the constructor body.
            Yes that is what the Sun compiler does.

            I was also curious what exactly what the specification says about what it should do.

            If it is required to do the code insertion then there should be a verification rule. I certainly couldn't find one.

            I did find the following in both the JLS and the VM Spec in the "Creation of New Class Instances" sections.

            +"This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or _implicit_ invocation of a superclass constructor (using super). "+

            That would suggest that a compiler is free to leave it out and then the VM would be responsible for calling the parents ctor. It doesn't even say which ctor it must call in that case, so presumably the VM could use a best match algorithm based on the current ctors parameters.
            • 3. Re: what is an empty constructor?
              EJP
              Yes that is what the Sun compiler does.
              And every other Java compiler.