Inheritance & Polymorphism Flashcards
What is inheritance in OOP?
Inheritance allows one class (subclass) to inherit attributes and methods from another class (superclass), establishing a parent-child relationship.
What is the purpose of the super keyword in Java?
The super
keyword refers to the immediate parent class, used to access parent class fields, methods, or constructors.
How do access modifiers impact inheritance?
Public: Accessible everywhere.
Protected: Accessible within the same package and by subclasses.
Default: Accessible within the same package.
Private: Accessible only within the class.
What are the benefits of inheritance?
Code reusability: Avoids redundancy.
Hierarchical modeling: Reflects real-world relationships.
Extensibility: New classes can be added without affecting existing code.
What are the three main types of inheritance in Java?
Single Inheritance: One subclass inherits from one superclass.
Multilevel Inheritance: A class inherits from a subclass.
Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
What is polymorphism in OOP?
Polymorphism allows entities to take on different forms, enabling methods or objects to behave differently based on their context.
What is method overloading?
Overloading allows multiple methods in the same class to have the same name but different parameter types or counts.
What is method overriding?
Overriding occurs when a subclass redefines a method from its superclass to provide specific behavior.
When should you use inheritance versus composition?
Use inheritance for “is-a” relationships (e.g., Dog is an Animal).
Use composition for “has-a” relationships or to increase flexibility (e.g., Car has an Engine).
Why prefer interfaces over abstract classes?
Interfaces offer more flexibility, as a class can implement multiple interfaces, while it can only extend one abstract class.
What is the difference between overloading and overriding?
Overloading: Same method name, different parameters, occurs in the same class.
Overriding: Subclass provides a new implementation for a parent class method.
What are best practices for using inheritance?
Use it for clear “is-a” relationships.
Prefer composition when possible.
Avoid deep hierarchies to reduce complexity.