Unit 9 Inheritance And Polymorphism FRQ (a) (b) (c) PENCIL AND PAPER ONLY. SHOW ALL YOUR WORK CLEARLY.
Understanding the intricacies of inheritance and polymorphism is essential for mastering object-oriented programming concepts, especially when tackling free-response questions (FRQs) on exams. This article provides a comprehensive guide to approaching Unit 9 FRQs related to inheritance and polymorphism, focusing on pencil-and-paper solutions. We will systematically break down each part—(a), (b), and (c)—with clear explanations, detailed work, and examples to help you succeed.
---
Overview of Inheritance and Polymorphism in Java
Before diving into the FRQ-specific strategies, it’s important to review the core concepts.
What is Inheritance?
- Inheritance allows a class (subclass or child class) to acquire properties and behaviors from another class (superclass or parent class).
- Facilitates code reuse and logical hierarchy.
- Example: A class `Dog` inherits from `Animal`, gaining attributes like `name` and methods like `eat()`.
What is Polymorphism?
- Polymorphism enables objects of different classes to be treated as instances of a common superclass.
- Allows method overriding, where a subclass provides a specific implementation of a method defined in the superclass.
- Example: Both `Dog` and `Cat` override the `makeSound()` method, but the correct version is called based on the actual object type.
Approach to FRQ (a) (b) (c): Pencil-and-Paper Strategy
The key to excelling in FRQs involving inheritance and polymorphism is to:
- Carefully read and understand the question prompts.
- Sketch class diagrams if necessary.
- Write clear, step-by-step code with explanations.
- Show reasoning for each decision, especially when dealing with method overriding and object references.
---
Part (a): Designing the Class Hierarchy
Understanding the Requirements
- Usually, part (a) asks you to define classes, fields, constructors, and methods.
- Focus on the core attributes and behaviors.
- Identify relationships (e.g., inheritance, composition).
Step-by-Step Solution Approach
- Identify the superclass(es): For example, if the problem involves different shapes, the superclass might be `Shape`.
- Define subclasses: For example, `Circle`, `Rectangle`, extending `Shape`.
- Declare fields: For example, `radius` for `Circle`, `length` and `width` for `Rectangle`.
- Write constructors: Initialize fields, possibly calling superclass constructors with `super()`.
- Implement methods: Such as `area()`, `perimeter()`, with appropriate overriding where needed.
Sample Skeleton for Part (a)
```java public abstract class Shape { // common attributes if any public abstract double area(); public abstract double perimeter(); }public class Circle extends Shape {
private double radius;
public Circle(double r) {
radius = r;
}
@Override
public double area() {
return Math.PI radius radius;
}
@Override
public double perimeter() {
return 2 Math.PI radius;
}
}
```
Note: Always include access modifiers, constructors, and method signatures clearly.
---
Part (b): Implementing a Method with Polymorphism
Understanding the Task
- Often, part (b) asks to write a method that takes a superclass reference and invokes overridden methods to demonstrate polymorphism.
Step-by-Step Solution Approach
- Define the method signature: For example, a method that takes a `Shape` object.
- Use the object reference: Call methods like `area()` or `perimeter()`.
- Explain dynamic binding: The actual method invoked depends on the runtime object type.
Example Method
```java public double totalArea(Shape[] shapes) { double total = 0; for (Shape s : shapes) { total += s.area(); // dynamic binding ensures correct method } return total; } ``` Key Point: Show that even though the array is of `Shape`, the overridden methods in subclasses are called at runtime.---
Part (c): Analyzing or Modifying Code for Inheritance and Polymorphism
Understanding the Question
- Part (c) may require you to:
- Predict the output of code involving polymorphic references.
- Modify existing code to fix errors.
- Extend the hierarchy with new subclasses.
Step-by-Step Solution Approach
- Trace code execution line-by-line: Focus on object creation and method calls.
- Identify the actual object type: Even if referenced as a superclass, determine which method is invoked.
- Explain behavior: Describe how polymorphism affects the method calls.
Example Analysis
Suppose the code is: ```java Shape s = new Rectangle(4, 5); System.out.println(s.area()); ```- Even though `s` is of type `Shape`, the `area()` method of `Rectangle` is called.
- The output depends on the `Rectangle` implementation.
Modifying the Code
- To add a new subclass, say `Square`, extend `Shape`:
public Square(double s) {
side = s;
}
@Override
public double area() {
return side side;
}
@Override
public double perimeter() {
return 4 side;
}
}
```
---
Common Pitfalls and Tips for Success
- Always include the @Override annotation to ensure correct overriding.
- Use clear, descriptive variable names to improve readability.
- Comment your code to explain your reasoning, especially when dealing with method calls and inheritance hierarchies.
- Double-check method signatures match between superclass and subclasses.
- Remember dynamic binding: method calls are resolved at runtime based on the actual object type, not the reference type.
- Sketch diagrams if needed to visualize class relationships and object interactions.
---
Practice Example: Full Walkthrough
Suppose the FRQ states:
> "Given an abstract class `Animal` with a method `makeSound()`, and subclasses `Dog` and `Cat` overriding `makeSound()`, write code to:
> (a) define these classes,
> (b) create an array of `Animal` references containing a `Dog` and a `Cat`,
> (c) write a method to print the sounds of all animals."
Solution:
(a) Define the classes:
```java
public abstract class Animal {
public abstract void makeSound();
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof");
}
}
public class Cat extends Animal {
@Override
public void makeSound() {
System.out.println("Meow");
}
}
```
(b) Create the array:
```java
Animal[] animals = { new Dog(), new Cat() };
```
(c) Write the method:
```java
public void printSounds(Animal[] animals) {
for (Animal a : animals) {
a.makeSound(); // invokes the correct overridden method
}
}
```
Expected output:
```
Woof
Meow
```
This example demonstrates all key concepts: class design, inheritance, method overriding, polymorphism, and method invocation.
---
Summary and Final Tips
- Always read the prompt carefully to understand what classes, methods, or behaviors are being asked for.
- Sketch class diagrams if it helps clarify relationships.
- Write code step-by-step, explaining your reasoning.
- Demonstrate understanding of polymorphism by showing how overridden methods are invoked.
- Use pencil-and-paper solutions to clearly illustrate your thought process, which can even help identify errors or alternative approaches.
- Practice a variety of FRQs to become comfortable with different scenarios involving inheritance and polymorphism.
---
Remember: Each part of an FRQ builds on your understanding of object-oriented principles. Show all your work clearly, and your explanations will shine through, maximizing your chances of earning full credit!