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:
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.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.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.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
- this can be used to refer current class instance variable.
- this can be used to invoke current class method (implicitly)
- this() can be used to invoke current class constructor.
- this can be passed as an argument in the method call.[TBD]
- this can be passed as argument in the constructor call.[TBD]
- 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)
Did you understand the first 3 usages of this keyword in the blog