📌IS A 관계(is a relationship, inheritance) 는 일반적인 개념과 구체적인 개념의 관계 - 상속으로 연결
'~은 ~이다' 의 관계
ex) 소는 동물이다.
class Animal {
}
.
.
.
class Cow extends Animal {
}
.
.
.
📌HAS A 관계(has a relationship, association) 는 일반적인 포함 개념의 관계 - 상속 사용 X
class Computer {
CPU cpu;
Memory memory;
}
.
.
.
- TV class = 부모
- SmartTV class = 자손
TV t = new SmartTV(); → 가능
SmartTV s = new TV(); → 불가능
SmartPhone ph2 = new MobilePhone();
MobilePhone ph2 = new SmartPhone("010-999-333", "Nougat"); ph2.playApp();
- 클래스 Employee(직원)은 클래스 Regular(정규직)와 Temporary(비정규직)의 상위 클래스
- 필드: 이름, 나이, 주소, 부서, 월급 정보를 필드로 선언
- 생성자 : 이름, 나이, 주소, 부서를 지정하는 생성자 정의
- 메소드 printInfo() : 인자는 없고 자신의 필드 이름, 나이, 주소, 부서를 출력
- 클래스 Regular는 위에서 구현된 클래스 Employee의 하위 클래스
- 생성자 : 이름, 나이, 주소, 부서를 지정하는 상위 생성자 호출
- Setter : 월급 정보 필드를 지정
- 메소드 printInfo() : 인자는 없고 "정규직"이라는 정보와 월급을 출력
package inhertest;
class Employee {
private String name, depart, address;
private int age, pay;
public Employee(String name, int age, String add, String dep) {
this.name = name;
this.age = age;
this.address = add;
this.depart = dep;
}
public void PrintInfo() {
System.out.println("이름: " + name);
System.out.println("나이: " + age);
System.out.println("주소: " + address);
System.out.println("부서: " + depart);
}
public void setPay(int pay) {
this.pay = pay;
}
public int getPay() {
return pay;
}
}
class Regular extends Employee {
public Regular(String name, int age, String add, String dep, int pay) {
super(name, age, add, dep); // 부모 클래스의 필드 가져오기
setPay(pay); // 부모 클래스의 함수를 가져올 때는 super 사용 안해도 가능
}
public void PrintInfo() {
super.PrintInfo(); // 자식 클래스와 부모 클래스 함수 이름이 같기 때문에 super 붙여야 함
System.out.println("고용형태: 정규직");
System.out.println("월급: " + getPay());
}
}
public class PolyTest {
public static void main(String[] args) {
Employee ep = new Regular("민정", 28, "경기도 평택시", "IT부", 5000000);
ep.PrintInfo();
}
}