상속 이란 새로운 클래스를 작성할때 기존에 존재하는 클래스를 물려받아 이용한다. 기존의 클래스가 가진 멤버를 물려받기 때문에 새롭게 작성해야 할 코드의 양이 줄어드는 효과가 있다. 이때 자신의 멤버를 물려주는 클래스를 부모클래스라고 하고 상속받는 클래스를 자식 클래스라고 한다.
class Person {
void breath() {
System.out.println("숨쉬기");
}
void eat() {
System.out.println("밥먹기");
}
void say() {
System.out.println("말하기");
}
}
class Student extends Person {
void learn() {
System.out.println("배우기");
}
}
class Teacher extends Person {
void teath() {
System.out.println("가르치기");
}
}
public class Inheritance1 {
public static void main(String[] args) {
Student s1 = new Student();
s1.breath();
s1.learn();
Teacher t1 = new Teacher();
t1.eat();
t1.teath();
}
}
// Parents 클래스의 멤버들을 상속받음
오버라이딩은 자식 클래스에서 부모 클래스로부터 물려받아 메서드를 재정의 하는것을 말한다.
class Parents {
void method1() {
// 부모 클래스의 메서드
}
}
class Child extends Parents {
@Override
void method1() {
//자식 클래스에서 메서드 내용 재정의
}
}
부모 클래스의 생성자 호출은 상위 클래스를 의미하는 super라는 키워드에 ()를 붙인 super()을 통해 이루어진다. 부모 클래스 호출은 무조건 자식 클래스 생성자 첫 줄에서 이루어진다. 만약 자식의 생성자 내부에 부모 클래스의 생성자를 따라 작성하지 않았다면 자동적을 컴파일러는 자식 클래스의 생성자 첫 줄에 super();을 추가한다.
class Car{
int wheel;
int speed;
String color;
Car(String color){
this.color = color;
}
}
class SportsCar extends Car{
int speedLimit;
SportsCar(String color, int speedLimit) {
super(color); // 상위 클래스의 생성자
this.speedLimit = speedLimit;
}
}
public class SuperConstructor {
public static void main(String[] args) {
SportsCar sportsCar = new SportsCar("red", 330);
System.out.println(sportsCar.color);
System.out.println(sportsCar.speedLimit);
}
}