As we discussed in previous questions that we can overload a constructor so if we keep return type for a constructor it will be treated as a normal method.
Note: Compiler gives a warning message that method has a constructor name.
Example
public class Main { String Main(){ System.out.println("Hello World"); return "Hello w3schools.com"; } public static void main(String[] args) { Main object = new Main(); System.out.println(object.Main()); } } |
Output
Hello World
Hello w3schools.com |
Java interview questions on constructor
- Default constructor
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- Constructor chaining in java
- Parameterized constructor in java
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?