DEV Community

Pavithra Saravanan
Pavithra Saravanan

Posted on

Java Constructor

What is constructor?
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes.

  • A constructor must have the same name as the class it belongs to.
  • Constructors are automatically called when an object is created using the new keyword.
  • Constructors are used to initialize the object's data members and set up the initial state of the object.

Types of Constructors:

  1. Default Constructor:
    If you don't explicitly define any constructors in your class, the Java compiler will automatically provide a default constructor. This constructor takes no arguments and initializes the object's fields with default values.

  2. Parameterized Constructor:
    A parameterized constructor allows you to pass values as arguments when creating an object, enabling you to initialize the object's fields with specific values.

  3. Copy Constructor:[TBD]
    A copy constructor is used to create a new object that is a copy of an existing object of the same class.

What is this keyword?

There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object.

Image description

Usage of Java this keyword

Here is given the 6 usage of java this keyword.

  1. this can be used to refer current class instance variable.
  2. this can be used to invoke current class method (implicitly)
  3. this() can be used to invoke current class constructor.
  4. this can be passed as an argument in the method call.[TBD]
  5. this can be passed as argument in the constructor call.[TBD]
  6. this can be used to return the current class instance from the method.[TBD]

Reference link:
https://www.javatpoint.com/this-keyword

Top comments (1)

Collapse
 
payilagam_135383b867ea296 profile image
Payilagam

Did you understand the first 3 usages of this keyword in the blog