[JAVA] 상속(this/super/promotion)
2023. 5. 17. 20:09ㆍLanguages/JAVA
💬 기억하고 싶거나 공부한 내용을 기록중입니다 :) 부족한 점이 많을 수 있어, 매일 배워가고 있습니다.
1️⃣ 클래스(class) : 상속(inheritanc)에서 this 또는 super
1. 정의
| this. | super. |
| 클래스의 객체 주소가 저장된 참조 변수 | 부모 클래스의 객체 주소가 저장된 참조 변수 |
2. this.
public class SuperGuitar { // 부모 클래스
String modelGuitar;
String colorGuitar;
}
public class Guitar extends SuperGuitar{
int numGuitar;
Guitar(String modelGuitar, String colorGuitar, int numGuitar){
this.modelGuitar = modelGuitar;
this.colorGuitar = colorGuitar;
this.numGuitar = numGuitar;
}
3. super
public class SuperGuitar {
String modelGuitar;
String colorGuitar;
public SuperGuitar(String modelGuitar, String colorGuitar) {
this.modelGuitar = modelGuitar;
this.colorGuitar = colorGuitar;
}
}
public class Guitar extends SuperGuitar{
int numGuitar;
Guitar(String modelGuitar, String colorGuitar, int numGuitar){
super(modelGuitar, colorGuitar);
this.numGuitar = numGuitar;
}
}
2️⃣ 클래스(class) : 자동 타입 변환(promotion)
- 클래스의 변환은 부모 클래스와 자녀 클래스가 상속 관계에 있는 경우에 가능하다
- 클래스의 변환은 자동 타입 변환(promotion)과 강제 타입 변환(casting)이 있다.
- 자동 타입 변환은 자동으로 타입 변환이 이루어지는 것을 말한다
| 부모클래스타입 참조변수 = new 자녀클래스타입(); |
- 주의사항
1) 부모 타입으로 자동 변환된 경우, 부모 클래스에서 선언된 필드와 메소드로만 접근이 가능하다.
2) 단, 자녀 클래스에서 메소드가 재정의(오버라이딩) 되었다면, 오버라이딩된 메소드가 대신 호출된다.
//부모 클래스
public class SuperFruit {
int numFruit = 1;
public void eat() {
System.out.println("과일을 먹는다");
}
}
//자녀 클래스
public class Fruit extends SuperFruit{
int numFruit = 3;
@Override
public void eat() {
System.out.println("과일을 "+ numFruit + "개 먹는다");
}
}
public class FruitMain {
public static void main(String[] args) {
SuperFruit fruit = new Fruit();
System.out.println(fruit.numFruit); // 결과 : 1, 오버라이딩 안됨
fruit.eat(); // 결과 : 과일을 3개 먹는다, 오버라이딩 됨
}
}
'Languages > JAVA' 카테고리의 다른 글
| [JAVA] 컬렉션 프레임워크 (0) | 2023.05.22 |
|---|---|
| [JAVA] 클래스(강제 형변환) (0) | 2023.05.18 |
| [JAVA] 생성자, 접근 제한자, 상수, 상속 (0) | 2023.05.16 |
| [JAVA] 클래스, getter/setter, 인스턴스(instance)/정적(static) (0) | 2023.05.15 |
| [JAVA] 클래스 구성 범위, 참조 변수 선언, 객체 생성 (0) | 2023.05.10 |