Okay so I have an assignment where I have to create a class with a set of private properties, which I have done. It gets tricky because I’m fairly new to java programming (or programming in general) and am not very practiced in encapsulation. I have not used getters/setters or constructors before. I understand the getter/setter methods, but have yet to understand any of the information online for constructors, or even understand their purpose.
I have to create getters/setters and constructors for each of the properties so it would seem I should learn to use these methods. If anyone could give me an example of a class with a constructor and explain what the constructor is doing, and why I would use it it would be nice.
Thank you ahead of time.
First off, welcome to the programming world 🙂
Lets look at a simple example.
Say you want to program a class to represent a Square. When you create a Square object, you have to give the Square certain properties, such as the length of each side. This is where constructors come into play.
The class layout looks like this, note the length_of_each_side variable is not assigned a value.
You can have a default constructor that will give you a predefined Square if you do not specify the size of the square.
or you can allow someone to specify the size of the square
If I want to create a pre-defined Square (length 1), it would look like this
If I want to create a Square and specify the length of 55, it would look like this