Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Whichever material I refer to, its mentioned to have a no-arg constructor in a JavaBean.
My doubt is that the compiler creates a default no-arg constructor if it doesn't encounter any constructor(s) in the program. So, why there is a need to create a no-arg constructor?

What I have tried:

I've referred the solutions in a few forums in which they've mentioned that there has to be a no argument constructor so that the tools that need to automatically create an instance of the Java Bean can do so, without complex mechanisms to figure out what parameters need to be passed and how to gain access to those parameters. But the compiler already creates one so why should we create a default no-arg constructor? Thanks in advance for your solutions.
Posted
Updated 26-Sep-18 1:43am

1 solution

If there is no constructor then default is constructor without arguments.
Java
public class HelloWorld{
    HelloWorld(){
    System.out.println("test"+ l);
    }
     public static void main(String []args){
        System.out.println("Hello World");
    new HelloWorld();
     }
}

Result
Hello World test


But if you add a single char with argument then that's the only constructor you have. Defaults are gone.

public class HelloWorld{
    HelloWorld(String l){
    System.out.println("test");
    }
     public static void main(String []args){
        System.out.println("Hello World");
    new HelloWorld();
     }
}


Result

HelloWorld.java:7: error: constructor HelloWorld in class HelloWorld cannot be applied to given types; new HelloWorld(); ^ required: String found: no arguments reason: actual and formal argument lists differ in length 1 error
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900