Chapter 8 Flashcards
(17 cards)
What is inheritance in Java?
Inheritance allows one class (subclass) to inherit fields and methods from another class (superclass), enabling code reuse and hierarchy modeling.
How is inheritance implemented in Java?
Using the extends
keyword.
```java
class Subclass extends Superclass { }
~~~
What does the super
keyword do?
It refers to the parent class. Can be used to call:
- A superclass method:
super.methodName()
- A superclass constructor:
super(args)
(must be the first line in constructor)
What does super()
do specifically in a constructor?
Calls the constructor of the parent class. Java inserts it implicitly only if the parent has a no-argument constructor.
What is method overriding?
A subclass provides a specific implementation of a method already defined in the superclass. The method must have the same name, return type, and parameters.
How do you indicate a method is overridden?
Use the @Override
annotation above the method.
What is the difference between method overloading and overriding?
- Overriding: Same method name & parameters in parent-child relationship.
- Overloading: Same method name, different parameters in the same class.
What is polymorphism in Java?
The ability of a subclass object to be treated as an object of its superclass.
What members are inherited by a subclass?
All non-private fields and methods. private
members are not inherited directly.
Can a class extend more than one class?
No. Java supports single inheritance only.
What is the final
keyword used for in inheritance?
-
final
class: cannot be subclassed. -
final
method: cannot be overridden.
What’s the difference between an abstract class and an interface?
- Abstract class: Can have fields, constructors, and some implementation.
- Interface: Purely abstract (though Java 8+ allows default methods). Supports multiple inheritance.
When should you use abstract classes vs. interfaces?
- Use abstract class for “is-a” relationships with shared implementation.
- Use interface for unrelated types needing common behavior.
What’s the difference between inheritance and composition?
- Inheritance: “is-a” relationship (e.g., Dog is-an Animal).
- Composition: “has-a” relationship (e.g., Car has-an Engine).
What are the benefits of using inheritance?
- Code reuse
- Logical hierarchy
- Polymorphism
- Centralized maintenance
- Extensibility
What is constructor chaining in inheritance?
When a subclass constructor calls a superclass constructor using super()
.
Can a subclass override a private or static method?
-
private
: Cannot be accessed or overridden. -
static
: Can be redefined but not truly overridden (called shadowing).