- 객체 지향형 프로그래밍에서 가장 핵심적인 요소에 해당됨.
- 부모 클래스가 자식 클래스에게 자신의 멤버를 물려주는 것을 의미함. 부모에게 있는 필드 값과 메서드를 그대로 사용 가능하게 되는 것에 해당됨.
- 모든 클래스는 Object 클래스의 자식이다.
// 부모 클래스
public class Car{
...
}
// Car를 상속 받는 자식 클래스
public class Electriccar extends Car{
...
}
ElectricCar ecar 생성 -> Car(부모 클래스), ElectricCar ecar 둘 다 생성됨.ElectricCar 타입에서 메서드나 필드를 찾지 못하면 Car로 올라가서 찾게 됨.오버라이딩 vs 오버로딩
- 오버라이딩(Overriding) : 부모 클래스의 메서드를 자식 클래스에서 재정의해서 사용하는 것을 의미.
- 오버로딩(Overloading) : 메서드 이름은 동일하나 매개변수 수나 타입이 다른 메서드를 여러 개 정의하는 것을 의미.
// 부모 클래스
public class Animal {
private String name;
private String kinds;
public Animal() {
}
public Animal(String name, String kinds) {
this.name = name;
this.kinds = kinds;
}
// 부모 클래스의
public String bark() {
return "짖는다.";
}
}
// 자식 클래스
public class Dog extends Animal {
private int weight;
public Dog() {
}
public Dog(String name, String kinds, int weight) {
super(name, kinds);
this.weight = weight;
}
// 오버라이드 하는 메서드
@Override
public String bark() {
return "멍멍~ 짖는다.";
}
}
super(); -> Electriccar(); 순서// 부모 클래스
public class Product {
protected String code;
protected String name;
protected String brand;
protected int price;
// 부모 클래스 기본 생성자
public Product() {
System.out.println("부모 클래스의 기본 생성자 호출");
}
// 부모 클래스의 생성자
public Product(String code, String name, String brand, int price) {
this.code = code;
this.name = name;
this.brand = brand;
this.price = price;
}
}
// 자식 클래스
public class Desktop extends Product{
private boolean allInOne; // 일체 여부
// 자식 클래스의 기본 생성자
public Desktop(){
// super();가 먼저 호출됨. 기본적으로 이건 생략되어 있음.
System.out.println("자식 클래스의 기본 생성자 호출");
}
public Desktop(String code, String name, String brand, int price, boolean allInOne) {
// 자식 생성자에서 부모 생성자 초기화 가능
this.code = code;
super.name = name;
this.brand = brand;
super.price = price;
this.allInOne = allInOne;
}
}