상세 컨텐츠

본문 제목

상속 - 기본 생성자(java)

프로그래밍/JAVA

by RosetteNebula 2021. 1. 14. 20:33

본문

 

기본 생성자가 없고

다른 생성자가 있으면 기본 생성자는 자동으로 생성되지 않습니다

 

부모 클래스에 접근하는 방법은 super로 가능

 

People 클래스

public class People {
	public String name;
	public String ssn;
	
	//다른 생성자가 있으면 기본 생성자는 자동으로 생성되지 않음
	
	public People(String name, String ssn) {
		this.name = name;
		this.ssn = ssn;
	}
}

 

Student 클래스 (People 클래스 상속)

public class Student extends People{
	public int studentNo;
	
	public Student(String name, String ssn, int studentNo) {
		super(name, ssn);	//부모 People 생성자 호출, 첫 줄에 작성
		super.name = name;	//부모의 변수에 접근
		super.ssn = ssn;
		this.studentNo = studentNo;
		
	}
}

 

main 클래스

public class StudentExample {
	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);
	}
}

'프로그래밍 > JAVA' 카테고리의 다른 글

오버라이딩 - final 메소드(java)  (0) 2021.01.14
오버라이딩(java)  (0) 2021.01.14
상속(java)  (0) 2021.01.13
클래스 ArrayList(java)  (0) 2021.01.13
클래스 배열(java)  (0) 2021.01.13

관련글 더보기