Inheritance: extends, super, and overriding · Herança: extends, super, e 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.
Herança: construindo sobre uma classe
- Herança permite que uma classe reutilize campos e métodos de outra classe.
- A classe sobre a qual você constrói é a superclasse (pai); a nova classe é a subclasse (filho).
- Uma subclasse é-um tipo de sua superclasse: um
Dogé umAnimal.
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 e super
- Escreva
class Dog extends Animalpara tornarDoguma subclasse deAnimal. Dogautomaticamente recebe todos os métodos públicos deAnimal, comogetName().- O construtor da subclasse chama o construtor da superclasse primeiro com
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.
Overrideando um método
- Uma subclasse pode overridear um método herdado: dê-lhe a mesma assinatura, um novo corpo.
Dog'sspeak()substituiAnimal'sspeak()para objetosDog.- Métodos que ele não overridea (como
getName()) ainda são herdados inalterados.
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() — estenda, não substitua
- Às vezes você quer o trabalho do pai mais um pouco adicional.
- Dentro de um override,
super.describe()executa a versão da superclasse do método. - Então você adiciona ao seu resultado em vez de reescrevê-lo do zero.
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: uma subclasse se encaixa onde sua superclasse é esperada
- Porque um
Dogé umAnimal, você pode escreverAnimal a = new Dog("Spot");. - O tipo da variável é
Animal, mas o objeto realmente é umDog. - Esta regra "is-a" é o que torna a próxima aula — polimorfismo — possível.
Common mistakes
super(...)must be the first line of a subclass constructor.- Add
@Overrideso the compiler catches a wrong signature.
Erros comuns
super(...)deve ser a primeira linha de um construtor de subclasse.- Adicione
@Overridepara que o compilador pegue uma assinatura errada.
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.
Agora você tenta
- Cada tarefa lhe dá uma superclasse
Animalconcluída. Escreva ou complete a subclasse abaixo dela. - Um Harness oculto constrói seu objeto e verifica tanto o comportamento herdado quanto o novo.
- Pressione Run para compilar, depois Check answer. Seu código roda no servidor, então mesmo a primeira execução é rápida.
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. · Abaixo do Animal concluído, escreva uma classe Cat que estende Animal. Dê-lhe um construtor Cat(String name) que passe o nome para cima com super(name). Adicione nada mais — Cat deve herdar getName() gratuitamente.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete the class Cow (it already extends Animal). Override speak() so a Cow returns · decrescentes "Moo" instead of the default. getName() must still work (inherited). · Complete a classe Cow (ela já estende Animal). Overriding speak() para que um Cow retorne "Moo" em vez do padrão. getName() ainda deve funcionar (herdada).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Complete a classe Fish (ela já estende Animal). Overriding describe() para que retorne a descrição Animal mais ", and I can swim". Reutilize o trabalho do pai chamando super.describe() — não reescreva toda a frase.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.