Object-Oriented Programming Flashcards
5 cards from real AP CSA practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 5 Object-Oriented Programming flashcards as text
What is the correct way to create an object from the following class?
Answer: Car myCar = new Car("Red");
To create an object in Java, you use the `new` keyword followed by a call to the class's constructor. The `Car` class has a constructor `Car(String color)` that requires a `String` argument. Therefore, `Car myCar = new Car("Red");` correctly instantiates a `Car` object, passing "Red" as the color, and assigns it to the `myCar` variable.
How does encapsulation improve code quality?
Answer: By hiding the implementation details of a class.
Encapsulation is a core OOP principle that enhances code quality by bundling data and methods within a class and controlling access to its internal state. It primarily achieves this by hiding the implementation details of a class (e.g., making variables private) and providing public methods (getters and setters) for controlled interaction. This protects data integrity, reduces complexity, and makes code more modular and maintainable.
What is the output of the following code?
Answer: Bark
This code demonstrates polymorphism and method overriding. An `Animal` reference `myAnimal` is assigned a `Dog` object. When `myAnimal.makeSound()` is called, Java's runtime polymorphism ensures that the specific `makeSound()` method implemented in the `Dog` class (the actual object type) is invoked, rather than the `Animal` class's method. Therefore, the output will be "Bark".
Which of the following statements are true about method overloading and overriding?
Answer: Overloading occurs within the same class.
Method overloading occurs within the same class when multiple methods share the same name but have different parameter lists (different method signatures). Method overriding, on the other hand, requires inheritance, where a subclass provides a specific implementation for a method already defined in its superclass. For a method to be overridden, it must have the exact same method signature (name, return type, and parameter list) as the method in the superclass.
What is true about abstract classes in Java?
Answer: Abstract classes can have both abstract and non-abstract methods.
Abstract classes in Java serve as blueprints for other classes and cannot be instantiated directly. They can contain a combination of abstract methods (declared without an implementation) and concrete methods (with full implementations). Any concrete class that extends an abstract class must provide implementations for all the abstract methods inherited from the abstract class, or it must also be declared abstract itself.