Contents
외울 것 요약C언어에서는 상속이 없고 Java,Python에 존재하는데
상속문제는 보통 Java에서 출제된다!
메서드 오버라이딩
부모클래스의 메서드를 자식 클래스에서 ‘재정의’한 것으로
메서드가 호출되면 자식클래스의 메서드가 우선순위임
(그치만 부모 객체를 만들고 중복된 메서드를 부른다면
부모 클래스의 메서드가 호출된다)
생성자
자식 클래스가 탄생하기 전에 부모 클래스의 기본 생성자가 호출됨
중간 개념 점검
- 자식이 오버라이드(재정의) 한 것은 자식 것으로 쓰인다.
- 자식이 재정의 하지 않은 것은 부모것으로 쓰인다
- 자식 클래스가 태어날 때는 본인 생성자보다 부모의 생성자를 먼저 호출
부모의 생성자가 여러개 + 명시적 호출
class Car {
String model;
int year;
Car() {
System.out.println("Car()");
}
Car(String model, int year) {
this.model = model;
this.year = year;
System.out.println("Car(" + model + "," + year + ")");
}
}
class ElectricCar extends Car {
int batteryCapacity;
ElectricCar() {
System.out.println("ECar()");
}
ElectricCar(String model, int year, int batteryCapacity) {
//부모 객체 생성(파라미터 있는 생성자)
super(model, year);
this.batteryCapacity = batteryCapacity;
System.out.println("Ecar(" + batteryCapacity + ")");
}
}
public class Main {
public static void main(String[] args) {
//생성자 중에 파라미터를 받는 생성자로 객체 생성
ElectricCar tesla = new ElectricCar("Tesla", 2021, 75);
}
}출력값은
Car(Tesla, 2021)
ECar(75)
근데 만약 super(model, year)가 없다면
출력값은
Car()
ECar(75)
가 된다. 무조건 부모 생성자를 거쳐야 하기 때문에 기본 생성자를 먼저
호출 시키기 때문이다.
부모 위에 또 부모가 있을 때 생성자
class Vehicle {
Vehicle() {
System.out.println("Veh()");
}
}
class Car extends Vehicle {
Car() {
System.out.println("Car()");
}
}
class ElectricCar extends Car {
ElectricCar() {
System.out.println("Ecar()");
}
}
public class Main {
public static void main(Stirng[] args) {
ElectricCar tesla = new ElectricCar();
}
}출력값:
Veh()
Car()
ECar()
외울 것 요약
- 자식이 상속받아 재정의 한 것은 재정의 한것으로 쓰인다.
- 자식이 태어날때는 상속 받은 모든 부모의 생성자를 위에서부터 호출한다.
- 자식이 부모의 생성자를 명시적으로 호출하는 함수는 super()이다.
- 만약 부모가 생성자가 여러개 라면, super()안의 매개변수로 조절한다.
Share article