In this tutorial, we will learn about the Constructors in Java, or its types, and how to use them with the help of examples.
Define Constructors in Java
- It is a member function of class.
- Its name same as class name .
- The constructor calls automatically whenever we create object of the class each time.
- The constructor can be parameterize but no return type even void.
- The use of constructor is it can be use to initialize the data value of data member of the class as well as it can be use to open file or database that can be use with object.
- In a class we can define more than one constructor and this will be called constructor overloading.(function overloading).
- Constructor always be define with public scope.
Syntax
Syntax of Constructorsclass ClassName { ClassName() { } }
Types of Constructor
- Default constructor
- Parameterized constructor
Default constructor in Java
A constructor that has no parameter is know as Default constructor in Java. This constructor provides the default values to the object depending on the type.
Example of Default constructor in Java
Input Value
Default constructor in Javapublic class consv { public consv(){ System.out.println("no constuctor"); } public static void main(String[] args){ consv d = new consv(); } }
Let’s run the code
Output Value
Parameterized Constructor
A constructor that has parameter is know as Parameterized constructor in Java.
Example Of Parameterized Constructor
Input Value
Parameterized Constructorpublic class consv { private String name; public consv(String n) { System.out.println("parameterized Construction"); this.name = n; } public String getName(){ return name; } public static void main(String[] args){ consv d = new consv("Basic engineer"); System.out.println(d.getName()); } }
Let’s run the code
Output Value
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about JAVA Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments