11-1. 상속
필드나 메소드를 중복하여 클래스를 생성하게 될 때
매번 클래스에 입력해주는 것보다는 상속을 이용하여 작업한다.
부모클래스(조상클래스, 슈퍼클래스, 상위클래스, 확장클래스) : Product자식클래스(후손클래스, 서브클래스, 하위클래스, 파생클래스) : SmartPhone, Tv, Desktop
public class SmartPhone extends Product{
private String mobileAgency;
public SmartPhone() {
super();
System.out.println("안녕 나는 자식 클래스 스마트폰이야!");
}
public SmartPhone(String brand, String pCode, String pName, int price, String mobileAgency) {
// 방법1 super.brand = brand; 부모클래스의 필드를protected로 변경한다.
/* 방법2
super.setBrand(brand);
super.setPCode(pCode);
super.setPName(pName);
super.setPrice(price);
*/
// 방법3
super(brand, pCode, pName, price);
this.mobileAgency = mobileAgency;
}
public String getMobileAgency() {
return mobileAgency;
}
public void setMobileAgency(String mobileAgency) {
this.mobileAgency = mobileAgency;
}
}
클래스 이름 뒤에 'extends 부모클래스이름' 을 붙여 필드와 메소드를 상속받아 사용할 수 있다.
그래서
public static void main(String[] args) {
SmartPhone smartPhone = new SmartPhone("LG", "vega", "베가", 10000, "LG");
System.out.println(smartPhone.information());
}
이렇게 information() 메소드를 호출하여 사용할 수 있다.
그러면
smartPhone.information()은 상속받은 메소드 Product의 inforamtion를 호출한 것이다.
public String information() {
return "brand : " + brand + ", pCode : " + pCode + ", pName : " + pName + ", price : " + price;
}
출력값 : brand : Apple, pCode : MAC, pName : 몰라, price : 250000
# 오버라이딩
여기서 자식클래스 SmartPhone의 필드인 String mobileAgency를 추가하여 출력하고 싶다면,
새롭게 information 메소드를 만들면 된다.
@Override
public String information() {
return super.information() + ", mobileAgency : " + mobileAgency;
}
출력값 : brand : Apple, pCode : MAC, pName : 몰라, price : 250000, mobileAgency : KT
(※ 오버로딩은 같은 이름의 메소드를 조금씩 다르게 해서 여러개 만드는 것)
상속받고 있는 부모클래스의 메소드를 자식클래스에서 재정의(재작성)하는 것
오버라이딩한 메소드에는 @Override 애노테이션을 붙여주자
11-2. 다형성
부모타입 자료형으로 자식 객체를 다루는 경우
Parent p2 = new Child1();
p2.printParent();
((Child1)p2).printChild1();
p2는 부모타입이지만 클래스 형 변환으로 자식 객체를 사용할 수 있다.
그럼 왜? 다형성을 사용하는가?일단은 배열을 사용할 수 있다.
상속과 객체생성 차이....
Override : 동적메소드 는 자식클래스의 것을 먼저 가져온다.
그 외는 모두 다운캐스팅 해줘야 사용할 수 있다.
'JAVA > JAVA수업' 카테고리의 다른 글
#13. API, I.O(Input/Output) (0) | 2023.07.19 |
---|---|
#12. 추상클래스, 인터페이스, 예외처리 (0) | 2023.07.18 |
#10. 오버로딩, static, 객체배열, list (0) | 2023.07.14 |
#9. 객체지향, 클래스, 접근제한자, 생성자, 메소드, 오버로딩 (0) | 2023.07.13 |
#8. 테스트 첫번째날/ 과제 (0) | 2023.07.12 |