부모 클래스의 기능을 자식 클래스가 물려받는 것
부모클래스에서 작성한 기능을 재사용하기 위해
class 클래스명 extends 부모클래스명{
...
}
public static void main(String[] args) {
Student st = new Student();
st.breath();
st.learn();
Teacher t = new Teacher();
t.eat();
t.teach();
}
}
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 teach() {
System.out.println("가르치기");
}
}
자식클래스에서 부모클래스로부터 받아온 메서드를 재정의하는 것
자식에 맞는 기능으로 맞춰 동작하기 위해
부모클래스의 생성자 호출
public static void main(String[] args) {
Leader leader = new Leader();
leader.say();
}
}
class Student{
void learn() {
System.out.println("배우기");
}
void eat() {
System.out.println("밥먹기");
}
void say() {
System.out.println("선생님 안녕하세요");
}
}
class Leader extends Student{
void lead() {}
void say() {//메서드 오버라이딩
System.out.println("선생님께 인사");
super.say(); //선생님 안녕하세요 출력
}
}