[개체지향] 상속
상속
- OOP의 핵심
- 다형성의 기반
- 재사용성
inheritance :번역 : 상속 유전이란것이 좀더 명확함.
이미 존재하는 클래스(부모클래스(parent class),기반클래스(base class))를 기반으로 새 클래스(자식클래스 child 파생클래스 derived)를 만드는 방법.
자식 클래스가 부모 클래스를
- 상속받았다
- 파생되었다
- extends되었다.
- 한 종류이다(is a)
상속 예시
public class Person{
private String firstName;
private String lasttName;
protected String email; //teacher에서만 수정가능하게 하기위함
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
this.email = String.format("%cs@pocu.academy", firstName.toLowerCase().charAt(0), lastName.toLowerCase());
}
public String getFullName(){
return String.format("%s %s",firstName,lastName);
public void changeName(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
public String getEmail(){
return this.email;
}
}
public class Student extends Person{
private Major major;
public Student(String firstName, String lastName){
super(firstName,lastName);
}
public Major getMajorOrNull(){
return this.major;
}
public void setMajor(Major major){
this.major = major;
}
}
public class Teacher extends Person{
private Department department;
public Teacher(String firstName, String lastName, Department department){
super(firstName,lastName);
this.department = department;
}
public Major getDepartment(){
return this.department;
}
public void setDepartment(Department department){
this.department = department;
}
public void setmail(String email){
super.email = email;//this
}
}
다이어그램 자식이 부모를 가르키는 화살표로 표시
접근제어자 정리 아래로 갈수록 제한적.
- public
- protected
- 기본/패키지
- private
| 접근제어자 | 클래스내부 | 같은패키지 | 자식클래스 | 외부 |
|---|---|---|---|---|
| public | o | o | o | o |
| protected | o | o | o | x |
| 기본/패키지 | o | o | x | x |
| private | o | x | x | x |
부모A 자식B new A()로 만든 개체는 new B()로 만든 개체의 public 멤버 변수에 직접 접근할 수 있다.
public class FullTimeTeacher extends Teacher{
private int officeNumber;
public FullTimeTeacher(String firstName, String lastName, Department department){
super(firstName,lastName,department);
}
public int getOfficeNumber(){
return this.officeNumber;
}
public void setOfficeNumber(int officeNumber){
this.officeNumber = officeNumber;
}
}
public class PartTimeTeacher extends Teacher{
private int weelyHours;
public PartTimeTeacher(String firstName, String lastName, Department department){
this(firstName,lastName,department,0);
}
public PartTimeTeacher(String firstName, String lastName, Department department, int hours){
super(firstName,lastName,department);
this.weeklyHours = hours;
}
public int getWeeklyHours(){
return this.weelyHours;
}
public void setOfficeNumber(int hours){
this.weelyHours = hours;
}
}
is a
- 상속 관계
- 수학에서 부분 집합 관계
has a
- 컴포지션 관계
상속 vs 컴포지션
- has -a : 컴포지션
- is-a : 상속
Teacher teacher = parttime;
Person person = parttime;
//compile OK
Person person = student;
Student actuallyStudent = person;
//compile error
Person person = student; //implicit casting
person.getMajorOrNull();
//compile error
Person person = student;
Student actuallyStudent = (Student)person;
//compile OK
Student student = (Student)teacher;
//compiler error
Person person = student;
Teacher teacher = (Teacher)person;
//compile ok, ClassCastException
instanceof
RTTI(run time type identification)
person instanceof Student // true
person instanceof Teacher // false
Person person0 = new Student("Leon", "Kim");
Person person1 = new Teacher("Pope","Kim", Department.COMPUTER_SCIENCE);
Teacher teacher = null;
if(person0 instanceof Teacher){
teacher = (Teacher) person0; //null
}
if(person1 instanceof Teacher){
teacher = (Teacher) person1; //person1
}
Person person = new PartTimeTeacher("Pope","Kim", Department.COMPUTER_SCIENCE,10);
if(person instanceof Teacher){ //true
}
getClass
FullTimeTeacher teacher = new FullTimeTeacher(...);
Class c = teacher.getClass();
- 실행중에 개체의 클래스 정보를 얻어올 수 있음
getClass().getName()
FullTimeTeacher teacher = new FullTimeTeacher(...);
teacher.getClass().getName(); //academy.pocu.FullTimeTeacher
- 클래스명을 반환
- 패키지 경로까지 포함.
사용때
- 클래스 이름을 찾을때
- 메서드,멤버 변수등도 찾을때
- 로그 메시지 출력할때
Object
java의 모든 클래스는 Object라는 클래스를 상속
entity
데이터 베이스의 데이터를 저장한다면 그걸 엔티티라함