I’m new to java, but I like the language and I want to become as good as possible but I still have some difficulties with the “class” thing.
I understand what a class is and what objects are but still I cant understand well getters and setters
I know a class has
- Instance variables
- Constructors
- Methods
- Setters and getters ?
I can’t understand well why do I need them and if I should write those inside a constructor.
Also like to point out that I’ve read several internet articles but
- those were to much “technical”
- they just write a code without instance variables, constructors so I can’t understand very well
Your help is very appreciated even if you are a beginner like me ^^
Edit:
For example how i should use the setters and getters here?
class Demo {
int a=4;
Int b;
public Demo () {
System.println("a is <than b")
};
public int Demo (int b) {
if (a<b)
System.out.println("a is < than b");
else
System.out.println("b is < than a");
}
}
You asked for a simple example, so I’ll give one. Suppose you’re designing a circle class. A circle can be characterized by its diameter:
A caller might want to know the diameter of the circle, so you add a getter:
You might also want to get the area of the circle, so you add a getter for the area:
And then you realize that using the radius rather than the diameter is easier for the internal methods of the circle. But you want to keep all the users of your class as is, to avoid breaking a lot of existing code. So you change the internals of the class without changing the interface:
And finally, you would like to change the diameter of the circle, so you add a setter:
But wait, a circle with a negative diameter makes no sense, so you make the method safer:
Had you precomputed the area at construction time, the setDiameter would have had to change the value of the area as well:
Getters and setters are just methods. But they follow a naming conventions that makes your code easy to grasp, and usable by a number of frameworks which rely on these conventions.