什么是java构造函数的点? [英] what's the point of java constructor?

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

问题描述

所以我在学习java。我有一个月了,我只是了解了构造函数。但我没有看到创建一个的整个目的。为什么和什么时候我想使用一个?我得到的主意,它没有一个主要的方法,你可以从你的主类调用一个构造函数。

So I'm learning java. I'm one month in and I just learned about constructors. But I don't see the whole purpose of creating one. Why and when would I ever want to use one? I get the whole idea that it does not have a main method and you can call a constructor from your main class. Anyone can enlighten me on this topic, it would help me a great deal.

推荐答案

构造函数是用来初始化/设置的

Constructors are what you use to initialize/set up the instances of your classes.

如果你有一个对象需要一些处理,然后才能使用(例如初始化成员),你应该在构造函数中这样做。

If you have an object that needs some processing before it is usable (initializing members for instance), you should do that in the constructor.

理想情况下,你不应该有部分构建对象(即活的对象,你拥有引用,但是还不可用)。没有构造函数,你将永久创建部分构建的对象,这是非常容易出错的。 (理论和实践并不总是匹配,但请牢记这一想法。)

Ideally, you should never have "partially built" objects (i.e. objects that are "live", that you hold a reference to, but that are not yet usable). Without constructors, you'd be permanently creating partially built objects, and that is very error-prone. (Theory and practice don't always match, but keep that idea in mind.)

这篇关于什么是java构造函数的点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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