Constructors in Java are what we use to create new objects. Furthermore, you use a constructor on initialize new objects. Constructors have the same name as the class and not return type.
Generally, you assign initial values to instance variables using a constructor. But you can also perform some initial tasks required when a new object is created.
The code below give an example of a constructor.
We have two types of constructors in Java.
- Constructor with no arguments
- Parameterized constructor
2. Constructors with no arguments
These constructors require not arguments. In this way you can create an object even if you don’t have the attributes. Take for example, the code below.
The constructor for circle has no parameters. However, when a new circle is created, it automatically has a radius of 50. Therefore if you run the code below, you will have an output of 50.
3. Parameterized Constructors
Sometimes, you will need a constructor that accepts one or more parameters. You specify the parameter inside braces after the constructor name. An example is given below
In the same way, you can run create a circle using the code below.
Running the above code would also produce similar result to the previous one. 50 is printed out. But notice that in this constructor, you pass 50 as a parameter.
Finally bear in mind, that two or even more constructors can be in the same class.
4. Creating New Objects
Just as you know, objects are create from classes. You use the new keyword to create new objects from classes.
Note the three steps involved in creating new objects
- Declaration: Here, you specify a variable name as an object type
- Instantiation: You use the new keyword
- Initialization: Assign initial values