1. 상속
자식 클래스가 부모 클래스가 가지고 있는 요소들에 접근 할 수 있도록 하고 요소들을 가질 수 있도록 하는 것을 상속이라고 합니다.
extends
상속을 하는 방법은 extends 키워드를 이용합니다.
public class ParentDog {
}
public class ChildDog extends ParentDog {
}
extends 키워드를 이용한 상속은 다중 상속이 불가능하며 자식 클래스는 하나의 부모 클래스에서만 상속 받을 수 있습니다.
또한 조부모 클래스, 부모 클래스, 자식 클래스로 구성할 수도 있습니다.
public class GrandParentDog {
}
public class ParentDog extends GrandParentDog {
}
public class ChildDog extends ParentDog {
}
상속을 받는 요소
부모 클래스로 부터 상속을 받을 수 있는 요소는 변수와 메서드입니다.
public class ParentDog {
protected String color = "black";
static protected int age = 10;
protected void bark() {
System.out.println("왈왈!");
}
}
public class ChildDog extends ParentDog {
// color, age 변수와
// bark(); 메서드의 요소를 상속 받는다
}
public class Main {
public static void main(String[] args) {
// ChildDog 클래스에 변수나 메서드를 선언하지 않아도 접근할 수 있습니다.
ChildDog childDog = new ChildDog();
System.out.println(childDog.color);
childDog.bark();
}
}
ParentDog 상속받은 요소를 ChildDog에서 사용할 수 있습니다.
protected 지시자
접근 제어 지시자 protected를 선언할 경우 같은 패키지 뿐만 아니라 다른 패키지에서도 접근 가능하며, 상속도 같은 패키지, 다른 패키지 둘 다 접근이 가능합니다. 이 같은 특징은 public 지시자와 유사한 면이 있으며, public 지시자 다음으로 가장 열려있는 지시자 입니다.
package com.codelatte.inheritance.dog;
public class GrandParentDog {
String leg = "long";
void bite() {
System.out.println("으르릉! 깨물다");
}
}package com.codelatte.inheritance.dog;
public class GrandParentDog {
String leg = "long";
void bite() {
System.out.println("으르릉! 깨물다");
}
}
package com.codelatte.inheritance.dog;
public class ParentDog extends GrandParentDog {
protected String color = "black";
protected void bark() {
System.out.println("왈왈!");
}
}
package com.codelatte.inheritance.outdog;
import com.codelatte.inheritance.dog.ParentDog;
public class ChildDog extends ParentDog {
public void info() {
System.out.println(leg); // 접근 불가능
System.out.println(color);
}
public void howling() {
bite(); // 호출 불가능
bark();
System.out.println("아오오오~~");
}
}
2. 접근제어 지시자 복기
출처 : https://www.codelatte.io/courses/java_programming_basic/QP8G11751WNNK8IV
'JAVA' 카테고리의 다른 글
[JAVA]다형성 (0) | 2023.10.19 |
---|---|
[JAVA]상속과 생성자 (0) | 2023.10.18 |
[JAVA]String 메서드 (0) | 2023.09.21 |
[JAVA]String 객체와 문자열 상수 (0) | 2023.09.20 |
[JAVA]캡슐화 (0) | 2023.09.12 |