DEV Community

Mohamed Ajmal
Mohamed Ajmal

Posted on

Constructor in Java.

A specialized block of code that similar to method that is automatically invoked when an instance of class is created. It's primary purpose is to initialize the state of the new object, often by assigning initial values to instance variables. It is used to set default or user-defined values for the object's attributes

Key Rules

  1. Must match the exact name of the class,
  2. Must not have an explicit return type, not even void,
  3. Automatically called using the new keyword,
  4. Can use access modifiers (public, private, protected) but cannot be abstract, static, final, or synchronized. (TBD)

Types

  1. Default Constructor: Automatically provided by the Java compiler if no constructors are explicitly defined in the class. It initializes numeric fields to 0, boolean to false, and object references to null.

  2. No-Arg Constructor: A constructor explicitly written by the programmer that accepts no parameters.

  3. Parameterized Constructor: Takes one or more parameters to allow objects to be initialized with custom values at creation. (TBD)

  4. Copy Constructor: Used to create a new object by copying the data from an existing instance of the same class. (TBD)

Top comments (0)