Inheritance
Single inheritance in Java: superclass and subclass, the is-a relationship, inherited members and protected, the super(…) call and constructor order, the root class Object.
- 25 cards
- 4 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
A few cards from the deck
Inheritance: what is it?
Show the answer
The mechanism by which a class takes over the attributes and methods of another, which it can extend or change.
It avoids copying shared code:
Dog extends Animalgives Dog everything Animal does, and Dog only writes what is specific to it.What does running
new Puppy();print?
```java
class Animal {
Animal() { System.out.println("Animal"); }
}
class Dog extends Animal {
Dog() { System.out.println("Dog"); }
}
class Puppy extends Dog {
Puppy() { System.out.println("Puppy"); }
}`Animal,Dog,PuppyPuppy,Dog,AnimalPuppyonlyAnimal,Puppy
Show the answer
Animal,Dog,PuppyEach constructor starts by calling its parent's, implicitly through
super(). Execution climbs to the root, then the bodies run from the most general to the most specialised.In Java, a class declares its parent class with the keyword … and can have only ….
Show the answer
In Java, a class declares its parent class with the keyword extends and can have only one.
That is single inheritance. To take over several contracts, a class can however implement several interfaces.
Superclass: what is it?
Show the answer
A class from which another derives, and whose accessible members the latter takes over.
Also called parent class. In
class Dog extends Animal, Animal is the superclass: it knows nothing about Dog.To reuse its storage, a developer wants the Stack class to inherit from the Array class. What should you answer?
- Java forbids inheriting from a class used as internal storage
- A stack is not an array: it should contain one, not inherit from it
- Inheritance is only possible from an abstract class
- A subclass cannot add methods to those of its parent
Show the answer
A stack is not an array: it should contain one, not inherit from it
To inherit is to say "is a": the Stack would inherit index access, which breaks its last-in, first-out principle. Code reuse is done by composition: an attribute of type Array.