can enyone explain to me why we are use setter & getter | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

can enyone explain to me why we are use setter & getter

26th Oct 2017, 6:30 PM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar
4 Answers
+ 3
Basically, when you have a class you'll have private members of the class that you don't want people directly accessing. Setters are methods that you can call from the object in order to change those private variables without directly accessing them. The Getters are methods you can use to indirectly return the value of those variables. This is called encapsulation and it helps you keep those variables hidden away. Hope that helps out some with understanding what they are. EXAMPLE: private String name; public void setName(String name) { this.name = name; } public String getName() { return this.name; }
26th Oct 2017, 6:34 PM
AgentSmith
+ 2
Setter isn't for setting initial value, although you could use it to do that. Your constructor is going to handle your initial value typically. Setter is for any time you want to set that private variable. Change value EXAMPLE: MyClass obj = new MyClass(); obj.setName("Ehsan"); ------------------------------------------------------------ INPUT EXAMPLE: Scanner scnr = new Scanner(System.in); MyClass obj = new MyClass(); System.out.println("The object name is " + obj.getName()); System.out.println("Please enter a new name for the object: "); obj.setName(scnr.nextLine()); System.out.println("The object's new name is " + obj.getName());
26th Oct 2017, 7:52 PM
AgentSmith
0
yes I understood from your explain I understand that I use setter to put initial value of private attribute .but if I want to put anther value or I want user enter value how can I use that
26th Oct 2017, 6:48 PM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar
0
thanks
27th Oct 2017, 10:25 AM
Asmaa Mogahed Khalifa Osman
Asmaa Mogahed Khalifa Osman - avatar