728x90
상속
- 확장성, 재사용성: 부모의 생성자와 초기화 블록은 상속x
- 클래스 선언 시 extends 키워드를 명시: 자바는 다중 상속X
- 관계
- 부모(상위, Super) 클래스 : Person
- 자식(하위, Sub) 클래스 : Student
- 자식 클래스는 부모 클래스의 멤버변수, 메소드를 자신의 것처럼 사용할 수 있다
- Object 클래스는 모든 클래스의 조상 클래스 -별도의 extends 선언이 없는 클래스는 extends Object가 생략
- super 키워드생성자 호출 순서: 부모 생성자 호출 → 자식(호출된 클래스) 생성자 호출
public class Person {
String name;
int age;
public Person() {
System.out.prinln("Person 생성자");
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public class Student extends Person {
String major;
public Student() {
super(); // 부모의 기본생성자 호출
System.out.println("Student 생성자");
}
}
Student() 호출 시 출력:
Person 생성자
Student 생성자
- super를 통해 조상 클래스의 생성자 호출
만약 부모의 기본생성자가 만들어지지 않았으면 오류 O (두 생성자의 매개변수가 동일해야 함)
오버라이딩 (재정의, overriding)
- 상위 클래스에 선언된 메서드를 자식 클래스에서 재정의하는 것
- 하위 클래스의 접근 제어자 범위가 상위 클래스보다 크거나 같아야 함
- 부모가 public, 자식이 private (X) :조상보다 더 큰 예외를 던질 수 없음
- 부모가 private, 자식이 public (O)
메서드의 이름, 반환형, 매개변수(타입, 개수, 순서) 동일해야 한다
@override
-Annotation: 컴파일러가 보는 주석 → 해당 메서드가 재작성되었음을 알려줌
부모의 속성이 private → 자식 class에서 접근할 수 없음: getter, setter를 통해 접근
728x90
'Java' 카테고리의 다른 글
[자바/Java] 제네릭 Generics (0) | 2022.07.27 |
---|---|
[자바/Java] 클래스 다형성(Polymorphism) (0) | 2022.07.25 |
[자바/Java] 싱글톤(Singleton) 패턴, Static (0) | 2022.07.25 |
[자바/Java] 배열, 1차원 배열, 2차원 배열 정리 (0) | 2022.07.23 |
자바 정규식 (regex) / 정규식 테스트 (0) | 2022.04.29 |