← Java from Scratch
Lesson 39 of 88 · 10 XP
Inheritance
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
class Animal {
protected String name;
Animal(String name) { this.name = name; }
void eat() { System.out.println(name + " is eating"); }
}
class Dog extends Animal {
Dog(String name) { super(name); } // the parent's constructor — on the first line
void bark() { System.out.println(name + ": Woof!"); }
}
Dog d = new Dog("Rex");
d.eat(); // from Animal
d.bark();
Animal a = d; // a subclass object can be stored in a variable of the parent type
- a class has one parent (there's no multiple inheritance of classes — interfaces are for that);
protectedis visible to subclasses,privateisn't;final classforbids inheritance.
Task. Finish Warrior extends Character with an armour field: takeHit(int dmg) reduces the damage by the armour,
but to no less than 1; HP doesn't go below 0.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.