Challenge - 5 Problems
Abstract Class Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of abstract class method call
What is the output of this Java program that uses an abstract class and a subclass?
Java
abstract class Animal { abstract void sound(); } class Dog extends Animal { void sound() { System.out.println("Woof"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Attempts:
2 left
π‘ Hint
Look at which class is instantiated and which method is called.
β Incorrect
The abstract class Animal cannot be instantiated directly, but the variable 'a' holds a Dog object. Calling a.sound() calls Dog's implementation, printing 'Woof'.
π§ Conceptual
intermediateWhy use abstract classes?
Which of the following is the main reason to use an abstract class in Java?
Attempts:
2 left
π‘ Hint
Think about what abstract classes enforce and what they provide.
β Incorrect
Abstract classes let you share code among related classes and require subclasses to implement abstract methods, ensuring a common interface.
π§ Debug
advancedIdentify the compilation error
What error does this code produce when compiled?
Java
abstract class Vehicle { abstract void start(); } class Car extends Vehicle { void start() { System.out.println("Car started"); } } class Bike extends Vehicle { } public class Test { public static void main(String[] args) { Vehicle v = new Bike(); v.start(); } }
Attempts:
2 left
π‘ Hint
Check if all abstract methods are implemented in subclasses.
β Incorrect
Bike does not implement the abstract method start(), so it must be declared abstract or implement the method. Otherwise, compilation fails.
π Syntax
advancedCorrect abstract method declaration
Which option shows the correct way to declare an abstract method in an abstract class?
Java
abstract class Shape { // method declaration here }
Attempts:
2 left
π‘ Hint
Abstract methods have no body and use the 'abstract' keyword before the return type.
β Incorrect
The correct syntax is 'abstract void draw();' without a method body. Option A has wrong keyword order, C has a body which is not allowed, D lacks 'abstract' keyword.
π Application
expertNumber of objects created
Given the code below, how many objects are created when main runs?
Java
abstract class Fruit { Fruit() { System.out.println("Fruit created"); } } class Apple extends Fruit { Apple() { System.out.println("Apple created"); } } public class Main { public static void main(String[] args) { Fruit f = new Apple(); } }
Attempts:
2 left
π‘ Hint
Remember how constructors work in inheritance and abstract classes.
β Incorrect
Only one object is created: an Apple instance. The Fruit constructor runs as part of Apple construction, but no separate Fruit object is created.
