클래스 안의 인스턴스 변수에 접근하는 메소드
package GetterSetter;
public class Person {
private String name;
private int age;
//get, set 메소드 작성(name)
public void setName(String name) {
//다른 클래스에서는 public을 가져다 쓸 수 있다
this.name = name ; //this는 인스턴스 객체를 의미
//Private의 name = Public의 name
}
public String getName() {
return name;
}
// get, set 메소드 작성(age)
public void setAge(int age) { //여기서 int 의 i 대문자 쓰면 에러남
this.age = age;
}
public int getAge() {
return age;
}
}
package GetterSetter;
public class App {
public static void main(String[] args) {
Person p1 = new Person();
// p1은 참조변수
// p1.name = "펭수";
// p1.age = 7;
System.out.println(p1);
Person p2 = p1;
System.out.println(p2);
p1.setName("펭수");
p2.setName("헹수");
System.out.println(p1.getName());
System.out.println(p2.getName());
p1.setAge(7);
System.out.println(p1.getAge());
System.out.println(p2.getAge());
}
}