java 기초 공부 내용 정리(상속, 오버라이딩)

홍준성·2022년 6월 3일
0

java 기초 공부

목록 보기
19/39

상속

부모 클래스의 기능을 자식 클래스가 물려받는 것

상속 사용 목적

부모클래스에서 작성한 기능을 재사용하기 위해

상속 방법

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("가르치기");
	}
}

상속 시 주의할 점

  1. 다중 상속은 지원하지 않는다.
  2. 클래스 앞 final 키드는 다른 클래스가 상속 불가

오버라이딩

자식클래스에서 부모클래스로부터 받아온 메서드를 재정의하는 것

사용 목적

자식에 맞는 기능으로 맞춰 동작하기 위해

부모클래스, 자식클래스 필드 모두 사용하는 방법

  • 부모 클래스 필드 사용 방법: super
  • 자식 클래스 내 필드 사용 방법: this

super()

부모클래스의 생성자 호출

  • 무조건 자식 클래스의 생성자 첫 줄에서 이루어짐
  • 작성하지 않을 시, 컴파일러가 자동 호출
	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(); //선생님 안녕하세요 출력
	}
}
profile
준성이의 개발자 공부 velog

0개의 댓글