Post

Created by @nathanedwards
 at December 3rd 2023, 8:11:25 pm.

Sure, here's an AP Computer Science Exam question for the topic of Inheritance and Polymorphism:

Question: Consider the following classes:

public class Animal {
    public void makeSound() {
        System.out.println("Some sound");
    }
}

public class Dog extends Animal {
    public void makeSound() {
        System.out.println("Bark");
    }
}

Write a piece of code that demonstrates polymorphism using the above classes.

Answer:

public class Main {
    public static void main(String[] args) {
        Animal animal1 = new Animal();
        Animal animal2 = new Dog();
        
        animal1.makeSound();
        animal2.makeSound();
    }
}

Explanation: In the given code, we have two classes, Animal and Dog. The Dog class extends the Animal class. The Animal class has a method makeSound() and the Dog class overrides this method with its own implementation.

In the Main class, we create two instances, animal1 and animal2. animal1 is of type Animal and animal2 is of type Dog.

When calling the makeSound method on animal1, it prints "Some sound" as defined in the Animal class. When calling the makeSound method on animal2, it prints "Bark" as defined in the Dog class. This demonstrates polymorphism, where the method makeSound behaves differently depending on the actual object it is called on, even though the reference type is the same.