Inheritance: extends, super, and overriding
Inheritance: building on a class
- Inheritance lets one class reuse another class's fields and methods.
- The class you build on is the superclass (parent); the new class is the subclass (child).
- A subclass is-a kind of its superclass: a
Dogis anAnimal.
상속: 클래스 확장하기
- 상속은 한 클래스가 다른 클래스의 필드와 메소드를 재사용할 수 있게 합니다.
- 확장하는 기존 클래스는 superclass(부모)이며, 새로운 클래스는 subclass(자손)입니다.
- 서브클래스는 슈퍼클래스의 일종입니다:
Dogis anAnimal입니다.
extends and super
- Write
class Dog extends Animalto makeDoga subclass ofAnimal. Dogautomatically gets every public method ofAnimal, likegetName().- The subclass constructor calls the superclass constructor first with
super(...).
extends과 super
class Dog extends Animal을 작성하여Dog을Animal의 서브클래스로 만듭니다.Dog은Animal의 모든 public 메소드(예:getName())를 자동으로 상속받습니다.- 서브클래스 컨스트럭터는 먼저
super(...)을 사용하여 슈퍼클래스 컨스트럭터를 호출합니다.
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Rex");
System.out.println(d.getName()); // Rex (inherited from Animal)
System.out.println(d.speak()); // Woof (Dog's own version)
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String getName() { return this.name; }
public String speak() { return "some sound"; }
}
class Dog extends Animal {
public Dog(String name) {
super(name); // run Animal's constructor
}
public String speak() { // override Animal's speak()
return "Woof";
}
}
Overriding a method
- A subclass can override an inherited method: give it the same signature, a new body.
Dog'sspeak()replacesAnimal'sspeak()forDogobjects.- Methods it does not override (like
getName()) are still inherited unchanged.
메소드 오버라이딩
- 서브클래스는 상속된 메소드를 오버라이딩할 수 있습니다: 동일한 시그니처를 가지되 새로운 바디를 가집니다.
Dog의speak()이Animal의speak()를Dog객체로 교체합니다.- 오버라이딩하지 않은 메소드(예:
getName())는 그대로 상속됩니다.
super.method() — extend, don't replace
- Sometimes you want the parent's work plus a little more.
- Inside an override,
super.describe()runs the superclass version of the method. - Then you add to its result instead of rewriting it from scratch.
super.method() — 대체하지 않고 확장
- 때로는 부모의 작업 加上 약간의 추가 기능이 필요할 수 있습니다.
- 오버라이딩 내부에서
super.describe()은 메소드의 슈퍼클래스 버전을 실행합니다. - 그런 다음 결과에 추가하거나, 처음부터 다시 작성하지 않습니다.
public class Main {
public static void main(String[] args) {
Bird b = new Bird("Tweety");
System.out.println(b.describe());
// I am an animal named Tweety, and I can fly
}
}
class Animal {
private String name;
public Animal(String name) { this.name = name; }
public String describe() { return "I am an animal named " + this.name; }
}
class Bird extends Animal {
public Bird(String name) { super(name); }
public String describe() {
return super.describe() + ", and I can fly"; // reuse, then add
}
}
is-a: a subclass fits where its superclass is expected
- Because a
Dogis anAnimal, you can writeAnimal a = new Dog("Spot");. - The variable's type is
Animal, but the object is really aDog. - This "is-a" rule is what makes the next lesson — polymorphism — possible.
is-a: 서브클래스는 슈퍼클래스가 기대되는 위치에 적합합니다
Dog이 is anAnimal이므로,Animal a = new Dog("Spot");를 작성할 수 있습니다.- 변수의 타입은
Animal이지만, 객체 자체는 실제로는Dog입니다. - 이 'is-a' 규칙이 다음 수업인 다형성을 가능하게 합니다.
Common mistakes
super(...)must be the first line of a subclass constructor.- Add
@Overrideso the compiler catches a wrong signature.
흔한 실수
super(...)은 서브클래스 컨스트럭터의 첫 번째 줄이어야 합니다.- компилятор가 잘못된 시그니처를 포착할 수 있도록
@Override을 추가하십시오.
Now you try
- Each task gives you a finished
Animalsuperclass. Write or complete the subclass below it. - A hidden Harness builds your object and checks both inherited and new behaviour.
- Press Run to compile, then Check answer. Your code runs on the server, so even the first run is fast.
이제 직접 해보기
- 각 과제는 완성된
Animal슈퍼클래스를 제공합니다. 아래에 서브클래스를 작성하거나 완성하십시오. - 숨겨진 Harness가 객체를 생성하고 상속된 동작과 새로운 동작을 모두 확인합니다.
- Run을 눌러 컴파일한 후 Check answer를 누르십시오. 코드가 서버에서 실행되므로 첫 실행도 빠릅니다.
Below the finished Animal, write a class Cat that extends Animal. Give it a constructor Cat(String name) that passes the name up with super(name). Add nothing else — Cat should inherit getName() for free.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete the class Cow (it already extends Animal). Override speak() so a Cow returns "Moo" instead of the default. getName() must still work (inherited).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete the class Fish (it already extends Animal). Override describe() so it returns the Animal description plus ", and I can swim". Reuse the parent's work by calling super.describe() — do not rewrite the whole sentence.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.