constructor overloading is a feature in Java programming that allows developers to create multiple constructors with different parameters. These constructors have the same name but different types of arguments, Hence all these constructors are considered as overloaded constructors.
public class ConstructorOverloading {
public ConstructorOverloading() {
System.out.println("no-arg constructor");
}
public ConstructorOverloading(int i) {
System.out.println("int argument constructor");
}
public static void main(String[] args) {
ConstructorOverloading object = new ConstructorOverloading();
ConstructorOverloading object2 = new ConstructorOverloading(2);
}}
For constructors inheritance and overriding concepts are not applicable but overloading is applicable.
Question- Can interfaces contain constructor in Java?
No, Interfaces can not contain constructors. Every class in Java including abstract Class can contain a constructor but interfaces can not.
Recursive Invocation of Constructor
The recursive method call is a runtime exception saying stack overflow error but if in Java program there is a chance of recursive constructor invocation then code will not compile and we will get compile time error-“java: recursive constructor invocation”.
public class ConstructorOverloading {
public ConstructorOverloading() {
this(10);
}
public ConstructorOverloading(int i) {
this();
}
public static void main(String[] args) {
}
}
Any Argumnet Constructor
If the parent class contains any argument constructor then while writing the child class we have to take care with respect to constructors.
Whenever we are writing any argument constructor it is highly recommended to write a no-argument(no-args) constructor also.
Exceptions in Constructors
If the Parent class constructor throws any checked exception then it is compulsory that the chiold class constructor should throw the same checked exception-“Unhandled exception: java.io.IOException”.
class Parent {
public Parennt() throws IOException {
}
}
class Child extends Parent{
}
Which of the following statements are valid about Constructors
Statments | Valid/Invalid |
---|---|
The main purpose of a constructor is to create an object | Invalid |
The main purpose of constructor is to perform initialization of an object | Valid |
The name of the constructor should not same as the class name | Invalid |
We can apply any modifier for constructor | Invalid |
If we are not writing no-args constructor then the compiler will generate the default constructor | Invalid |
The default constructor is always no-args constructor | Valid |
For constructors overloading and overriding both concepts are applicable | Invalid |
For constructor inheritance concept applicable | Invalid |
Interfaces can contain constructors | Invalid |
Recursive constructor invocation is a runtime exception | Invalid |