+ 1
can enyone explain to me why we are use setter & getter
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;
}
+ 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());
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
0
thanks