JAVA/Java 기초
상속 - inheritance
H_eh
2022. 5. 23. 19:54
상속을 이용하는 이유
-클래스 사이에 변수를 중복 선언하지 않아도 된다 (클래스의 간결화)
-계층적으로 분류 할 수 있다 (클래스 관리의 용이)
-클래스 재사용과 확장
자식 생성자를 만들 때 부모생성자 호출을 첫번째에 적어야 한다.
생성자가 하나 있으면 기본 생성자가 만들어 지지 않는다.
매개변수를 가진 생성자의 경우 부모 클래스의 기본생성자가 가장 먼저 호출된다.
protected :
- 같은 패키지 클래스에 접근 가능
- 다른 패키지 클래스에 접근 불가능
→ 같은 패키지의 서브 클래스에 접근 가능
→ 다른 패키지의 서브 클래스에 접근 가능 : 상속개념..
super :
예약어로 매개변수가 있는 생성자 호출하기
- 디폴트 생성자가 아닌 매개변수가 있는 생성자를 직접 구현해야 한다.
→ 어떤 생성자를 호출할 것인지 명시하는 예약어
class Human {
String name;
int age;
void show() {
System.out.println(name +" "+ age);
}
}
class Student extends Human {
String major; //자식클래스에서 추가되는 인스턴스 변수(name,age,show())그대로 물려받음
void pr() {
show();
System.out.println(major);
}
}
public class InherEx1 {
public static void main(String[] args) {
Human h = new Human();
h.name="세종";
h.age=32;
h.show();
Student s = new Student();
s.name="정조";
s.age=19;
s.major="컴퓨터공학";
s.pr();
}
}
class A {
A(){
System.out.println("생성자 A");
}
A(int n){ //생성자 오버로딩
System.out.println(n);
}
}
class B extends A{
B(){
System.out.println("생성자 B");
}
B(int n){ //생성자 오버로딩
super(n);
// 부모클래스의 매개변수가 있는 생성자가 호출된다.
// 없으면 기본 생성자가 호출된다.
System.out.println(n);
}
}
public class InherEx2 {
public static void main(String[] args) {
B b = new B(7); //생성자 호출
}
}
class Circle {
private int r; //필드 (인스턴스 변수)
public Circle(int r) { //생성자
this.r = r;
}
int get() { //메서드
return r;
}
}
class NCircle extends Circle {
String color;
NCircle(int r, String c){
super(r); //부모 생성자를 호출하는 것(line 6)
color = c;
}
void show() {
System.out.println("반지름: " + get() +", "+ color +"색");
}
}
public class InherEx5 {
public static void main(String[] args) {
NCircle n = new NCircle(10, "red");
n.show(); //반지름 10 red색
}
}
728x90
728x90