Thursday, November 19, 2009

Key Java Concepts II - Constructors

This post will focus on the concepts surrounding Constructors in Java. So, here we go...

  • Constructors MUST have the same name as class.
  • A constructor is invoked when an object is created.
  • Constructors don't have a return type.
  • Interfaces never have constructors.
  • Constructors cannot be inherited, thus they cannot be overridden.
  • Constructors can use any access modifier.
  • The compiler will create a default constructor, even if you don't create one yourself.
  • Every class has a constructor. Even an abstract class has one.
  • The default constructor is a no-arg constructor with a call to super().
  • The constructor can be directly invoked using another constructor only i.e using a call to super() or this().
  • Calls to this() or super() cannot be in the same constructor. Either one can exist, not both.
  • this() may appear as only the first statement in a constructor.
  • Constructors can call other constructors and they can call constructors again, however it's advisable to use a call to super() as early as possible to avoid the explosion of stack.
  • The call to super() can be a no-arg call or may have arguments passed to the super constructor.
  •  Its perfectly legal to have methods and constructor with the same name and in the same class. However it's not considered to be a good programming style.
 Illustration:

class Foo {
    Foo() {} // this is the constructor.
}

In this case, when the compiler compiles it, it generates a default constructor. So, for the compiler, the above code will look like:

class Foo {
    Foo {
         super();
    }
}



Stumble Upon Toolbar

No comments:

Post a Comment

Related Posts with Thumbnails