Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Language Fundamentals - Constructor Declarations

Syntax (JLS §8.8)

        modifiers ClassName(arguments) throwsClause {
            // Constructor body
        }

The modifers, ClassName, arguments, and throwsClause are optional.

[Note: all are optional in the sense that your class does NOT have to declare a constructor (see following on default constructors);however, if you do include a constructor modifiers, arguments and the throws clause are optional.]

  • a constructor can use the access modifiers public, protected or private or have no access modifier (package access)
  • a constructor can not use the modifiers abstract, static, final, native, synchronized or strictfp (JLS §8.8.3)
  • constructors are not considered class members, they are not inherited
  • if a class constructor is not declared, a default constructor is supplied by the compiler
            modifiers ClassName() {
                super();                
            }
    
  • the default constructor has the same access modifier as the class itself, either: public, protected, private or package (no modifier)
  • to prevent a class from being instantiated outside the class declaration you can create a private constructor.
Note

A method having the same name as the class is not treated as a constructor

    public void MyClassName() {}    // not a constructor
    public MyClassName() {}         // constructor

A constructor cannot have a return type.

Tips

  • a constructor body can include a return statement providing no value is returned

Traps

  • subclass with default constructor when the superclass does not have a no-args constructor or it's no-arg constructor has a throws clause
  • constructor declared with a return type


Source Package Import Class Interface Constructors
  Methods main() Identifiers Keywords Defaults Arrays
  Primitives # Literals char Literal String Literals Class Literals