为什么Default构造函数在实例化Object时需要在具有参数化构造函数的POJO文件中声明? [英] Why Default constructor need to declare in POJO file which has Parameterized Constructor while instantiating Object?

查看:112
本文介绍了为什么Default构造函数在实例化Object时需要在具有参数化构造函数的POJO文件中声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有构造器public User(int id, String name){...}的POJO类User. 但是,当我实例化User对象(如User u=new User())且没有参数时,Eclipse会给出错误,如未定义构造函数User().但是当我没有参数化的构造函数时,它可以正常工作.有人可以解释为什么它要求定义默认构造函数吗?

Suppose I have one POJO class User with a constuctor public User(int id, String name){...}. But when I instantiate the User object like User u=new User() with no parameter Eclipse gives error like The constructor User() is undefined. But it works fine when I have no parameterized Constructor. Can someone please explain why It requires to define default constructor?

推荐答案

仅在没有提供其他构造函数的情况下,才提供默认(无参数)构造函数.如果为类定义了单个构造器,则必须使用显式定义的构造器(即,在您的代码中)之一来实例化对象.当然,您可以定义自己的零参数,空构造函数(如果它可以满足您的尝试).

The default (no-parameter) constructor is ONLY provided if you have provided no others. If you define even a single constructor for your class, you MUST use one of the explicitly defined (ie, in your code) constructors to instantiate the object. You can, of course, define your own zero-parameter, empty constructor if that works for what you're trying to do.

why?

编译器提供了一个默认的构造函数,以便在未定义构造函数时可以实例化Object.但是,如果定义了参数构造函数,则意味着在创建该类的新实例时,应使用已传递的参数初始化其变量(或执行类似的操作).没有这些初始化,该对象可能无法以预期的方式运行.因此,编译器通过不定义默认构造函数(定义了默认构造函数)来防止此类情况的发生.

The compiler provides a default constructor so that the Object can be Instantiated when there are no constructors defined. But if you have defined a parametric constructor, it means that when you create a new instance of that class, its variables should initialized with the parameters you have passed(or do something similar). Without those initializations, the object might not behave in an expected way. Hence the compiler prevents such things from happening by not defining a default constructor(when you have defined one).

这篇关于为什么Default构造函数在实例化Object时需要在具有参数化构造函数的POJO文件中声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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