자바 상속
Java 상속(서브클래스 및 슈퍼클래스)
Java에서는 한 클래스에서 다른 클래스로 속성과 메서드를 상속할 수 있습니다. "상속 개념"을 두 가지 범주로 그룹화합니다.
- 하위 클래스 (자식) - 다른 클래스에서 상속하는 클래스
- 상위 클래스 (부모) - 상속되는 클래스
클래스에서 상속하려면 extends
키워드를 사용하십시오.
아래 예에서 클래스(하위 클래스)는 클래스(수퍼 클래스) Car
의 속성과 메서드를 상속합니다 .Vehicle
예시
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
protected
차량 의 수정자를 눈치채셨나요 ?
Vehicle 의 브랜드 속성을 access modifier 로 설정합니다 . 로 설정 하면 Car 클래스가 액세스할 수 없습니다.protected
private
"상속"을 사용하는 이유와 시기는?
- 코드 재사용성에 유용합니다. 새 클래스를 만들 때 기존 클래스의 속성과 메서드를 재사용합니다.
팁: 다른 작업을 수행하기 위해 상속된 메서드를 사용 하는 다음 장인 다형성 (Polymorphism) 도 살펴보십시오 .
최종 키워드
다른 클래스가 클래스에서 상속되지 않도록 하려면 다음 final
키워드 를 사용하십시오.
클래스 에 액세스하려고 하면 final
Java에서 다음 오류를 생성합니다.
final class Vehicle {
...
}
class Car extends Vehicle {
...
}
출력은 다음과 같습니다.
Main.java:9: error: cannot inherit from final Vehicle
class Main extends
Vehicle {
^
1 error)