Challenge - 5 Problems
Abstract Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of abstract method implementation
What is the output of the following Java code?
Java
abstract class Animal { abstract void sound(); } class Dog extends Animal { void sound() { System.out.println("Bark"); } } public class Main { public static void main(String[] args) { Animal a = new Dog(); a.sound(); } }
Attempts:
2 left
π‘ Hint
Look at which class implements the abstract method and what method is called.
β Incorrect
The abstract method sound() is implemented in Dog class. The object a is of type Dog, so calling a.sound() prints "Bark".
π§ Conceptual
intermediatePurpose of abstract methods
What is the main purpose of declaring a method as abstract in Java?
Attempts:
2 left
π‘ Hint
Think about what happens if a subclass does not implement an abstract method.
β Incorrect
Abstract methods have no body and require subclasses to implement them, ensuring specific behavior is defined in subclasses.
π§ Debug
advancedIdentify the compilation error
What error will this code produce?
Java
abstract class Shape { abstract void draw(); } class Circle extends Shape { // No draw() method implemented } public class Main { public static void main(String[] args) { Shape s = new Circle(); s.draw(); } }
Attempts:
2 left
π‘ Hint
Check if all abstract methods are implemented in subclasses.
β Incorrect
Circle does not implement the abstract method draw(), so it must be declared abstract or implement draw(). This causes a compilation error.
π Syntax
advancedCorrect syntax for abstract method declaration
Which option shows the correct way to declare an abstract method in Java?
Attempts:
2 left
π‘ Hint
Abstract methods have no body and must end with a semicolon.
β Incorrect
The correct syntax is to use 'abstract' before the return type and end with a semicolon without a method body.
π Application
expertNumber of abstract methods in a class
Given the following code, how many abstract methods does class B have?
Java
abstract class A { abstract void m1(); abstract void m2(); } abstract class B extends A { void m1() { System.out.println("Implemented m1"); } }
Attempts:
2 left
π‘ Hint
Count abstract methods not implemented in class B.
β Incorrect
Class B implements m1(), so only m2() remains abstract. Therefore, B has 1 abstract method.
