0
0
Javaprogramming~20 mins

Why inheritance is used in Java - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Inheritance Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why do we use inheritance in Java?

Inheritance allows one class to take properties and methods from another class. Why is this useful?

ATo reuse code and create a relationship between classes
BTo make the program run faster by skipping methods
CTo hide all methods from other classes
DTo prevent any changes in the parent class
Attempts:
2 left
πŸ’‘ Hint

Think about how sharing common features can save time and effort.

❓ Predict Output
intermediate
2:00remaining
Output of inheritance example

What will be the output of this Java code?

Java
class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}
class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}
public class Test {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();
    }
}
ARuntime error
BAnimal makes a sound
CCompilation error
DDog barks
Attempts:
2 left
πŸ’‘ Hint

Remember that the method called depends on the actual object type, not the reference type.

πŸ”§ Debug
advanced
2:00remaining
Identify the inheritance error

What error will this code produce?

Java
class Parent {
    void show() {
        System.out.println("Parent class");
    }
}
class Child extends Parent {
    void show(int x) {
        System.out.println("Child class: " + x);
    }
}
public class Test {
    public static void main(String[] args) {
        Child c = new Child();
        c.show();
    }
}
ARuntime error: NullPointerException
BOutput: Parent class
COutput: Child class: 0
DCompilation error: method show() not found in Child
Attempts:
2 left
πŸ’‘ Hint

Check if the Child class inherits the show() method without parameters.

πŸ“ Syntax
advanced
2:00remaining
Correct inheritance syntax

Which option shows the correct way to inherit a class in Java?

Aclass Child inherits Parent {}
Bclass Child implements Parent {}
Cclass Child extends Parent {}
Dclass Child uses Parent {}
Attempts:
2 left
πŸ’‘ Hint

Java uses a specific keyword to inherit from a class.

πŸš€ Application
expert
2:00remaining
Number of methods accessible via inheritance

Given these classes, how many methods can an object of class C call?

class A {
  void m1() {}
  void m2() {}
}
class B extends A {
  void m3() {}
}
class C extends B {
  void m4() {}
}
A4
B3
C2
D5
Attempts:
2 left
πŸ’‘ Hint

Count all methods from class C and its parents.