
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Constructor Chaining in Java
Constructors are similar to methods but,
- They do not have any return type.
- The name of the constructor is 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.
this() and super() are used to call constructors explicitly. Where, using this() you can call the current class's constructor and using super() you can call the constructor of the super class.
You can also call one constructor from another.
Calling a constructor of one class from other is known as constructor chaining. From normal (default) constructor you can call the parameterized constructors of the same class using this() and, from the sub class you can call the constructor of the super class using super()
Example
class Super{ Super(int data){ System.out.println("value is : "+ data); } } public class Sub extends Super{ Sub(int data) { super(data); } public static void main(String args[]){ Sub sub = new Sub(400); } }
Output
value is : 400
Advertisements