Programming Language/JAVA
[Java] Get, Set
나수비니
2023. 9. 27. 15:48
728x90
/*
Get and Set
1. private variables can only be accessed within the same class.
2. However, it's possible to access them if we provide public get and set methods.
3. get method returns the variable value, the set method sets the value.
*/
package GetterSetter;
public class Person {
private String name; //private = restricted access
//Getter : returns the value of the variable name.
public String getName() {
return name;
}
//Setter : takes a parameter newName and assigns it to the namevariable.
public void setName(String newName) {
this.name = newName;
}
}
public class Main {
public static void main(String[] args) {
// 에러발생 > Person 클래스에서 private 리턴타입으로 지정되어있기에
Person myObj = new Person();
myObj.name = "John"; // error
// setName 으로 name 변수 설정 >> getName으로 이름 받아내면 됨
Person myObj = new Person();
myObj.setName("John"); // Set the value of the name variable to "John"
System.out.println(myObj.getName());
}
}