Inheritance: extends, super, and overriding · Наследование: extends, super и переопределение
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.
Наследование: расширение класса
- Наследование позволяет одному классу переиспользовать поля и методы другого класса.
- Класс, от которого вы наследуете, называется суперкласс (родитель); новый класс — подкласс (потомок).
- Подкласс является разновидностью своего суперкласса:
DogявляетсяAnimal.
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, такие какgetName().- Конструктор subclasses вызывает конструктор superclass первым с
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'sspeak()заменяетAnimal'sspeak()для объектов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являетсяAnimal, вы можете написать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.
Теперь попробуйте сами
- Каждое задание предоставляет готовый
Animalsuperclass. Напишите или дополните subclass ниже него. - Скрытый 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. · Ниже готового класса Animal напишите класс Cat, который наследует Animal. Дайте ему конструктор Cat(String name), передающий имя вверх через super(name). Ничего больше не добавляйте — Cat унаследует getName() автоматически.
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). · Заполните класс Cow (он уже наследует от Animal). Переопределите speak(), чтобы объект Cow возвращал "Moo" вместо значения по умолчанию. getName() должен всё ещё работать (наследоваться).
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. · Заполните класс Fish (он уже наследует Animal). Переопределите describe() так, чтобы он возвращал описание из Animal плюс ", and I can swim". Переиспользуйте работу родителя, вызвав super.describe() — не переписывайте всё предложение целиком.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.