为什么javabean应该有一个no-arg构造函数? [英] Why should a javabean have a no-arg constructor?

查看:99
本文介绍了为什么javabean应该有一个no-arg构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论我提到哪种材料,都提到它在JavaBean中有一个无参数构造函数。

我怀疑编译器是否创建了一个默认的无参数构造函数,如果它没有遇到任何程序中的构造函数。那么,为什么需要创建一个无参数构造函数呢?



我尝试过:



我在几个论坛中引用了这些解决方案,他们提到必须有一个无参数构造函数,以便需要自动创建Java Bean实例的工具可以这样做,没有复杂的机制来确定需要传递什么参数以及如何获得对这些参数的访问。但是编译器已经创建了一个,那么我们为什么要创建一个默认的无参数构造函数呢?在此先感谢您的解决方案。

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.

推荐答案

如果没有构造函数,那么默认是没有参数的构造函数。

If there is no constructor then default is constructor without arguments.
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





但是如果你用参数添加一个char,那么这是你唯一的构造函数。默认值消失。





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


这篇关于为什么javabean应该有一个no-arg构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆