상속을 통해 하나의 클래스가 다른 클래스의 속성과 메서드를 물려받아 재사용

⇒ 코드의 재사용성을 높이고, 코드의 중복을 줄일 수 있음

기본 구조

class B {
    
}

class A extends B {  //클래스 A는 클래스 B를 상속받는다
    
}

inheritance

//구조
class Human {
	public void intro() {} //메서드
}

class Student extends Human {
	 
	 public void study() {} //메서드

}

public class Inheritance {
	public static void main(String[] args) {
	
	}
}
package chapter09.inheritance;

class Human {
	//변수
	int age;
    static String name;
	
	//생성자 (초기화 목적)
	Human(int age, String name) {
		System.out.println("=====Human 생성자======");
		this.age = age;
		this.name = name;
	}
	
	//메서드
		public void intro( ) {
			System.out.println("안녕, " + age + "살 " + name + "이야");
		}
}	
		
class Student extends Human { //상속은 extends라는 예약어 사용
	int stNum;
	String major;
	
	Student(int age, String name, int stNum, String major) {
		//super() 상위클래스를 부르는 역할  
		super(age, name); //부모클래스에 있는 생성자로 보내서 초기화를 시키겠다
		this.stNum = stNum;
		this.major = major;
		System.out.println("=====Student 생성자=====");
	}
	
	public void study() {
		System.out.println("스터디 스터디");
	}
}
	

public class Inheritance {

	public static void main(String[] args) {
		Human kim = new Human(29, "홍길동");
		kim.intro();
		
		Student lee = new Student(33, "이순신", 20241001, "경영");
		//⇒ 자식 생성자 들어감 ⇒super()로 부모 생성자 실행 ⇒ 자식 생성자 실행
		lee.intro();
		lee.study();
		lee.name = "김다희";     
        lee.intro();
       
		kim.intro();
		
		
	}
	 
}

<출력 결과>

=====Human 생성자====== 안녕, 29살 홍길동이야 =====Human 생성자====== =====Student 생성자===== 안녕, 33살 이순신이야 스터디 스터디 안녕, 33살 김다희이야 안녕, 29살 김다희이야

<설명>

Human kim = new Human(29, "홍길동");

⇒ 부모 생성자 실행

kim.intro();

⇒ 부모의 객체로 부모의 메서드 호출

⇒ 부모의 생성자, 부모의 메서드 실행됨.

Student lee = new Student(33, "이순신", 20241001, "경영"); ⇒ 자식 생성자 들어감

⇒super()로 부모 생성자 실행

⇒ 자식 생성자 실행