Hotel
package day07.encap.obj;
public class Hotel {//사용자 클래스
//public String str=new String("dd");-이는 public String str="dd";와 같다. 평소에 편하게 쓰는 것
private Chef chef;//=new Chef();-클래스를 멤버변수로 선언
//기본생성자
public Hotel() {
}
//생성자-클래스를 받는 생성자
public Hotel(Chef chef) {
this.chef=chef;
}
//getter, setter
public void setChef(Chef chef) {
this.chef=chef;
}
public Chef getChef() {
return chef;
}
}
Chef
package day07.encap.obj;
public class Chef {
public void cooking() {
System.out.println("요리사");
}
}
호텔 클래스에서 생성자와 getter setter를 쓸 때 셰프 클래스를 매개변수로 받았다.
이는 위에 멤버변수를 선언할 때 셰프 클래스를 멤버변수로 선언하였기에 가능한 것
이때 주목할 것은 클래스를 멤버변수로 받을 수 있고, 클래스를 매개변수로 받을 수 있다는 것이다.
Chef chef = new chef();를 짧게 줄여
Chef chef;로 표현한 것.
main
package day07.encap.obj;
public class MainClass {
public static void main(String[] args) {
//호텔클래스 사용
Hotel hotel = new Hotel();
//hotel.setChef(new Chef());
Chef chef = new Chef();
hotel.setChef(chef);
//getter
Chef c=hotel.getChef();
c.cooking();
System.out.println(chef==c);//true
}
}
요리사
true
chef==c가 true인 것은 getter와 setter를 이용할 때 멤버변수로 받은 셰프클래스를 사용하였기에,
getter의 리턴값도 chef이기 때문이다.
'JAVA' 카테고리의 다른 글
221012 다형성 (0) | 2022.10.12 |
---|---|
221012 클래스 받기 실습 (0) | 2022.10.12 |
221011 replaceAll 문자열 자르기 (0) | 2022.10.11 |
221011 getter setter 실습과 객체배열 (0) | 2022.10.11 |
221011 생성자와 getter setter 단축키 (0) | 2022.10.11 |