x

Java – Constructors

PREV     NEXT

Java Constructors:


  • A constructor is a special method in a class, used to initialize the object’s fields.
  • The name of the constructor is same as that of the class name.
  • Whenever a new object of its class is created, a constructor is invoked.
  • Every class has a constructor. Even if it is not defined, compiler would create a one implicitly.
  • Constructors do not have return type.

Example:


  • If no constructor is defined, the default constructor would initialize the instance variables to their default values (0 for numeric values, false for boolean type and null for reference types).

Parameterized Constructor:

We can also pass parameters to the constructors as we pass in methods.

Example:

  • The height and width of the Box are initialized with the values provided by the arguments passed while invoking the constructor.
  • Reference types can also be passed to the constructor.

    PREV     NEXT



Like it? Please Spread the word!