what's the point of java constructor?

后端 未结 7 1288
野趣味
野趣味 2021-01-07 15:24

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

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-07 15:34

    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.)

提交回复
热议问题