What is constructor in java or why constructor in java or what is use of constructor in java
Constructors are special method in java. It's part and partial of object creation in java language. whenever we try to create object of a class, all the properties of that must be initialised to provide response properly.
When ever we create object, some piece of code is executed automatically to perform initialisation, these piece of code is nothing but constructor. Hence we can say main objective of constructor is to perform initialisation for the newly created object's properties.
So as of now we can answer these questions.
1. What is constructor ?
Ans : Constructor is a special member function of a class that has some special functionality to initialise data member of class at object creation time.
2. What is use of constructor ?
Ans : Constructor is used to initialised newly created object's properties.
Example :
Here we have created three object of Employee class employee1, employee2, employee3. For all object creation constructor with their corresponding parameter will be called to initialised the object properties.
Example :
Example :
Employee employee1 = new Employee (123, "Santosh");
Similarly for employee2 and employee3 when object will be created into the memory their attribute values will be assign through constructors.
Type of constructors
There are two type of constructor
- Default / No argument Constructor.
- Parameterised Constructors.
Default Constructors
If we are not writing any constructors in our class then compiler will always generate default constructor in our class.
If we are writing at-least one constructor in our class then compiler won't generate default constructor in our class.
Hence a class contains at-least one constructor either programmer written or compiler generated.
Prototype for default Constructors
Default Constructor is always no argument constructor.
The access modifier of default constructor is same as class modifier
Default Constructor contains only one line that is no argument call to super class constructor.
Example :
Parameterised Constructors
Parameterised Constructor always takes argument as a input that has to be assign to object properties.
Example :
Above hi-lighted code is parameterised constructor which is taking two parameter id and name as input.
Rules to define constructors
## Constructor name and class name should be same.
## Programmer can not return value from constructors. No return type required to make constructors. If we declare return type for the constructor then there won't be any problem but it will be considered as normal method not constructor.
Example :
above hi-lighted code is example for constructor. let's see another example
The same code when i declare return type void then it's not constructor now it's turn into a normal method.
So we can have method like class name as well and this can be differentiated from constructor with the return type, constructor does not have return type but method always have return type.
## The only applicable modifier for constructors are public, private, protected, <default>. if you try to use any other modifiers static, final you will get compile time error.
Example
There this code will not compile because we have used static modifier here that is not allowed.
## There won't be any class without constructor. Each and every class will have al-least one constructor either programmer written or compiler generated
Use of super() and this()
super() and this() are used to make constructor call.
super() : Used to call Immediate Parent / Base class constructor.
this () : Used to call current class constructors.
The first line inside constructors should be either super() or this(). If we are not writing anyone then compiler will place super() as a first line inside constructor of your class.
Case (I) : We have to use either super() or this() only as the first line of constructor.
Example :
This code will not compile because super() is not the first line in constructor.
Case (II) : In the constructor we can use either super() or this() but not both simultaneously
Example :
both super() and this() can not be used simultaneously.
Case (III) : We can use super() and this() only inside constructors. if we are using anywhere else we will get compile time error.
Example :
Case (IV) : Compiler provide default super() but not this() inside your constructor.
Constructor overloading
A class can contain more than one constructor with same name but different argument and these constructor are considered as overloaded constructor.
Example :
Let's check how it work with application
Let's understand this when employee3 object created with double value , the constructor with double argument will be called and over there, there is this(10) written at the first line of constructor with int value that will call another constructor with int argument of the same class, now in the constructor with int argument there is this() written at the fist line that will call default constructor that class. now control goes to default constructor, in the default constructor there is no this() and super() so by default super() is there that will call parent class default constructor that is of an Object class.
So the fact is whenever an object is created, along with the constructor of that class corresponding constructor of all the parent class till the Object class is executed.
# Inheritance and overriding concept are not applicable for constructors.
# Every class in java including abstract class also can contains constructors but interface can not have constructor.
Example :
Case 1. # Recursive method call give runtime exception always but recursive constructor invocation is compile time error.
example showing recursive method call will cause runtime exception StackOverflowError.
Recursive constructor call will cause compile time error.
Case 2. # If parent class contains some constructor then while creating child class we will have to give some special attention about constructors.
valid case will work perfectly
valid case will work perfectly
This will not work, there will be compilation time error.
whenever we are writing any constructor with argument it's highly recommended to write no argument constructor also.
Case 3. # If parent class constructor throws some checked exceptions compulsory child class constructor same checked exception or it's parent otherwise code will not compile.
Child class also has to throws same exception or Parent of IOException.
This will be good child class also throwing IOException but child class can also throw Exception here.
Note : In case of RuntimeException base class and parent class constructor can throw any exception no problem will be there.
Constructor Chaining
Calling constructor from another constructor is called constructor chaining. whenever we are chaining constructor, the termination of chain will always be Object class constructor.
Constructor chaining is done by using this() and super() functions.
Example :
This way we can chain constructor.
Conclusion :
So far we have covered all the concept related to constructor. A constructor is typically used to initialise instance variables of newly created object.
Some fact about constructor. Let's see what you have learnt so far by answering these questions.
You have to give your answer as TRUE / FALSE
1. Every class contains constructers. [TRUE | FALSE]
2. Only concrete class can contains constructor but not abstract class. [ TRUE | FALSE]
3. The name of the constructor need not to be same as class name. [ TRUE | FALSE]
4. Return type is applicable for constructor. [ TRUE | FALSE ]
5. The only applicable modifier for constructors are public and default. [ TRUE | FALSE ]
6. If you declare return type for constructor, you will get compile time error. [ TRUE | FALSE]
7. Compiler will always generate default constructor. [ TRUE | FALSE]
8. The access modifier for default constructor is always default. [ TRUE | FALSE]
9. The first line in every constructor should be super(). [ TRUE | FALSE]
10. The fist line in every constructor should be this(). [ TRUE | FALSE]
11. Interface can contains constructors. [ TRUE | FALSE]
12. Overriding and Overloading concept are applicable for constructors. [ TRUE | FALSE ]
13. Inheritance concept are applicable for constructor. [ TRUE | FALSE]
Answer:
1. TRUE 2. FALSE 3. FALSE 4. FALSE 5. FALSE 6. FALSE 7. FALSE 8. FALSE 9. FALSE 10. FALSE. 11. FALSE. 12. FALSE. 13. FALSE
Let's discussed about some of the interview questions on constructors in java.
1. What is constructor chaining ?
Ans : Calling a constructor from another constructor is called constructor chaining. constructor chaining can be done by using this() function. this() function is used to call another constructor of the same class with required parameter. there is another function super() that called constructor of parent class according to their parameter. for example your can refer above description of constructor chaining.
2. Can you call child class constructor from parent class constructors ?
Ans : No you can not call child class constructor from parent class constructor but vice versa is possible means you can call parent class constructor from child class constructor through super() function.
3. Can you define a method name same as class name ?
Ans : Yes, You can make method name as your class name, but you should not make your method name like your class name.
4. Can you define return type for a constructors ?
Ans : No, Constructor does not have return type, although your can write return type before constructor there will not be any problem with compiler but JVM treat that as a normal method not as a constructor.
5. If Constructor and method name is same how compiler will identify which is constructor and which one is method ?
Ans : If you define constructor and method name same then constructor will be identified with it's return type, because constructors does not have any return type but method must have their return type.
Example :
6. Call we call constructor explicitly ?
Ans : No, constructors can not be called explicitly, it will be called automatically while creating object.
Also read :
No comments:
Post a Comment