English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 튜토리얼에서는 예제를 통해 Java의 thừa kế를 배웁니다.
thừa kế는 OOP(향상된 객체 지향 프로그래밍)의 중요한 기능 중 하나로, 기존 클래스에서 새로운 클래스를 정의할 수 있게 합니다. 예를 들어,
class Animal { // eat() 메서드 // sleep() 메서드 } class Dog extends Animal { // bark() 메서드 }
Java에서는 extends 키워드를 사용하여 클래스를 상속합니다. 여기서, 우리는 Animal 클래스에서 Dog 클래스를 상속했습니다.
Animal은 상위 클래스(부모 클래스 또는 기본 클래스)이며, Dog은 하위 클래스(하위 클래스 또는 파생 클래스)입니다. 하위 클래스는 상위 클래스의 필드와 메서드를 상속합니다.
상속은is-a관계가 있을 때, 두 클래스之间存在 is-관계가 있을 때, 상속을 사용합니다.
이곳에 몇 가지 예제가 있습니다:
자동차는 차량입니다.
오렌지는 과일입니다.
외과의사는 의사입니다.
개는 동물입니다.
class Animal { public void eat() { System.out.println("저는 먹을 수 있습니다"); } public void sleep() { System.out.println("저는 잠을 자릅니다"); } } class Dog extends Animal { public void bark() { System.out.println("저는 짖습니다"); } } class Main { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.eat(); dog1.sleep(); dog1.bark(); } }
출력 결과
저는 먹을 수 있습니다 저는 잠을 자릅니다 I can bark
여기서, 우리는 부모 클래스 Animal에서 Dog 하위 클래스를 상속했습니다. Dog 클래스는 Animal 클래스에서 eat()와 sleep() 메서드를 상속했습니다.
따라서, Dog 클래스의 객체는 Dog 클래스와 Animal 클래스의 멤버에 접근할 수 있습니다.
이전 강의에서 우리는 private와 public 접근 수식자를 배웠습니다.
private 멤버는 클래스 내에서만 접근할 수 있습니다
public 멤버는 어디서든 접근할 수 있습니다
또한 메서드와 필드를 protected로 설정할 수 있습니다. 보호된 멤버는 접근할 수 있습니다
클래스 내부
하위 클래스에서
같은 패키지 내에서
이 수식자 접근이 가능한 요약입니다.
수식자 | 클래스 | 패키지 | 하위 클래스 | 전체 |
---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
private | Yes | No | No | No |
protected | Yes | Yes | Yes | No |
class Animal { protected String type; private String color; public void eat() { System.out.println("저는 먹을 수 있습니다"); } public void sleep() { System.out.println("저는 잠을 자릅니다"); } public String getColor(){ return color; } public void setColor(String col){ color = col; } } class Dog extends Animal { public void displayInfo(String c){ System.out.println("저는 " + type); System.out.println("My 색은 " + c); } public void bark() { System.out.println("저는 짖습니다"); } } class Main { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.eat(); dog1.sleep(); dog1.bark(); dog1.type = "mammal"; dog1.setColor("black"); dog1.displayInfo(dog1.getColor()); } }
출력 결과
저는 먹을 수 있습니다 저는 잠을 자릅니다 I can bark 저는 포유류입니다 My 색은 검정입니다
여기서, Animal 클래스의 타입 필드는 보호되어 있습니다. 우리는 Main 클래스에서 이 필드에 접근했습니다
dog1.type = "mammal";
이 가능합니다. 왜냐하면 Animal과 Main 클래스가 같은 패키지(같은 파일)에 있습니다.
从上面的示例中,我们知道子类的对象也可以访问其超类的方法。
如果在超类和子类中都定义了相同的方法,会发生什么情况?
好吧,在这种情况下,子类中的方法将覆盖超类中的方法。例如,
class Animal { protected String type = "animal"; public void eat() { System.out.println("저는 먹을 수 있습니다"); } public void sleep() { System.out.println("저는 잠을 자릅니다"); } } class Dog extends Animal { @Override public void eat() { System.out.println("저는 개의 글을 먹습니다"); } public void bark() { System.out.println("저는 짖습니다"); } } class Main { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.eat(); dog1.sleep(); dog1.bark(); } }
출력 결과
저는 개의 글을 먹습니다 저는 잠을 자릅니다 I can bark
여기서 eat()은 상위 클래스 Animal과 서브 클래스 Dog에 모두 나타납니다. Dog의 객체 dog를 생성했습니다1.
当我们使用dog1객체가 eat() 메서드를 호출할 때, Dog 내부의 메서드가 호출되고, 상위 클래스의 동일한 메서드가 호출되지 않습니다. 이를 메서드 오버라이드라고 합니다.
위의 프로그램에서는 @Override 주석을 사용하여 컴파일러에게 메서드를 오버라이드 중임을 알렸습니다. 하지만 이는 필수적이지 않습니다. 다음 강의에서는 더 자세히 설명하겠습니다.메서드 오버라이드.
Animal의 서브 클래스에서 eat() 메서드를 호출하려면 super 키워드를 사용해야 합니다.
class Animal { public Animal() { System.out.println("저는 동물입니다"); } public void eat() { System.out.println("저는 먹을 수 있습니다"); } } class Dog extends Animal { public Dog(){ super(); System.out.println("저는 개입니다"); } @Override public void eat() { super.eat(); System.out.println("저는 개의 글을 먹습니다"); } public void bark() { System.out.println("저는 짖습니다"); } } class Main { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.eat(); dog1.bark(); } }
출력 결과
저는 동물입니다 저는 개입니다 저는 먹을 수 있습니다 저는 개의 글을 먹습니다 I can bark
Here, we use the super keyword to call the constructor through super(). Additionally, we use super.eat() to call the eat() method of the Animal superclass.
Note: The difference when calling constructors and super methods. For more information, please visitJava super 키워드.
There are five types of inheritance.
Single inheritance - Class B inherits only from class A.
Multi-level inheritance - Class B inherits from class A, and then class C inherits from class B.
Hierarchical inheritance - Class A is the superclass of B, C, and D.
Multiple inheritance -Class C extends interface A and B.
Mixed inheritance -Two or moreInheritanceMixing.
Java does not support multiple inheritance and mixed inheritance through classes. However, we can implement multiple inheritance in Java through interfaces. We will learn about interfaces in the next chapter.
가장 중요한 용도는 코드의 재사용성입니다. 부모 클래스에 존재하는 코드는 자식 클래스에서 다시 작성할 필요가 없습니다.
메서드 오버라이딩을 통해 런타임 파라다이ム을 구현하는 것이 가장 중요한 용도입니다. 다음 장에서는 파라다이ム에 대해 더 많은 정보를 배울 것입니다.