- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Constructors in Javan
Constructors are similar to methods and are different in the following sense.
They do not have any return type.
The name of the constructor is the same as the name of the class.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
A class can have more than one constructor.
Example
class A { public int a; //default constructor public A() { this(-1); } //parameterized constructor public A(int a) { this.a = a; } } public class Tester { public static void main(String[] args) { //new object created using default constructor A a1 = new A(); System.out.println(a1.a); //new object created using parameterized constructor A a2 = new A(1); System.out.println(a2.a); } }
Output
-1 1
- Related Articles
- Get all Constructors in Java
- What are constructors in Java?
- Type of Java constructors
- Can interfaces have constructors in Java?
- Can constructors be inherited in Java?
- Constructors of StringBuffer class in Java.
- Constructors of StringBuilder class in Java.
- Constructors of StringTokenizer class in Java.
- What are Default Constructors in Java?
- Are Multiple Constructors possible in Java?
- What are copy constructors in Java?
- What are parametrized constructors in Java?
- Java Interview Questions on Constructors
- Can we have generic constructors in Java?
- Difference between Constructors and Methods in Java

Advertisements