
IS-A 관계(is a relationship, inheritance) 는 일반적인 개념과 구체적인 개념의 관계
고양이는 동물이다
강아지는 동물이다.
위와 같은 관계입니다. 즉, 일반 클래스를 구체화 하는 상황에서 상속을 사용
HAS-A 관계(has a relationship, association) 는 일반적인 포함 개념의 관계
- HAS-A 관계에서는 상속을 사용하지 않는다.
- HAS-A 관계는 다른 클래스의 기능(변수 혹은 메서드)을 받아들여 사용
- 다형성은 상속을 통해 기능을 확장하거나 변경하는 것을 가능하게 해준다.
- 즉, 다형성은 형태가 같은데 다른 기능을 하는 것을 의미한다 (같은 동작이지만 다른 결과물이 나올때 다형이라고 생각하면 된다.)
- 이를 통해 코드의 재사용, 코드 길이 감소가 되어 유지보수가 용이하도록 도와준다.
SmartPhone ph2 = new MobilePhone();

- 클래스 Employee(직원)은 클래스 Regular(정규직)와 Temporary(비정규직)의 상위 클래스
- 필드: 이름, 나이, 주소, 부서, 월급 정보를 필드로 선언
- 생성자 : 이름, 나이, 주소, 부서를 지정하는 생성자 정의
- 메소드 printInfo() : 인자는 없고 자신의 필드 이름, 나이, 주소, 부서를 출력
✅Employee 구현
class Employee {
private String name;
private int age;
private String address;
private String department;
private int salary;
public Employee(String name, int age, String address, String department) {
this.name = name;
this.age = age;
this.address = address;
this.department = department;
}
public void printInfo() {
System.out.println("이름: "+this.name);
System.out.println("나이: "+this.age);
System.out.println("주소: "+this.address);
System.out.println("부서: "+this.department);
}
}
-클래스 Regular는 위에서 구현된 클래스 Employee의 하위 클래스
-생성자 : 이름, 나이, 주소, 부서를 지정하는 상위 생성자 호출
- Setter : 월급 정보 필드를 지정
- 메소드 printInfo() : 인자는 없고 "정규직"이라는 정보와 월급을 출력
✅Regular 구현
class Employee {
private String name;
private int age;
private String address;
private String department;
protected int salary;
public Employee(String name, int age, String address, String department) {
this.name = name;
this.age = age;
this.address = address;
this.department = department;
}
public void printInfo() {
System.out.println("이름: "+this.name);
System.out.println("나이: "+this.age);
System.out.println("주소: "+this.address);
System.out.println("부서: "+this.department);
}
public void setSalary(int salary) {
this.salary = salary;
}
}
class Regular extends Employee {
Regular (String name, int age, String address, String department, int salary) {
super(name, age, address, department);
setSalary(salary);
}
public void setSalary(int salary) {
super.salary = salary; //super
}
public void printInfo() { //함수 오버라이딩
super.printInfo();
System.out.println("정규직 월급: "+ super.salary);
}
}
public class EmployeeMain {
public static void main(String[] args) {
Employee employee = new Employee("홍길동", 27, "서울시", "디자인");
employee.printInfo();
System.out.println();
Employee employee2 = new Regular("김철수", 26, "서울시", "마케팅", 2_500_000);
employee2.printInfo(); //함수 오버라이딩, 폴리머피즘 적용
}
}
- 부모 클래스에서 만들어진 메서드를 자식 클래스에서 자신의 입맛대로 다시 재정의해서 사용하는 것