본문 바로가기
Programing/JAVA (& 혼공자Java)

자바(Java) - 상속2 (부모 생성자 호출)

by a.k.a DUKI 2020. 10. 28.
728x90
반응형

부모 생성자 호출

자식 객체 생성할때 부모 객체가 먼저 생성되고 그 다음 자식 객체가 생성된다.

 

  • 자식 생성자의 맨 첫 줄에서 부모 생성자가 호출된다.
public DmbCellPhone(){
	super();
}
public CellPhone(){ ... }

 

  • 명시적으로 부모 생성자를 호출하려는 경우
자식클래스(매개변수언언, ...){
	super(매개값, ...);
}

혼공자 유툽 참고

 

예시1) 부모 클래스

public class People {
	public String name;
	public String ssn;
	
	public People(String name, String ssn) {
		this.name = name;
		this.ssn = ssn;
	}
}

자식 클래스

public class Student extends People {
	public int studentNo;

	public Student(String name, String ssn, int StudentNo) {
		super(name, ssn); // 부모 생성자 호출
		this.studentNo = studentNo;
	}

}

자식 객체 이용

public class StudentEx {

	public static void main(String[] args) {
		Student student = new Student("홍길동", "123456-1234567", 1);
		System.out.println("name: " + student.name);
		System.out.println("ssn: " + student.ssn);
		System.out.println("studentNo: " + student.studentNo);
	}

}

 

 

 

 

본 내용은 #혼자공부하는자바 책을 참고해 공부하려 작성했습니다.

 

728x90
반응형

댓글