Inheritance allows one class to take properties and methods from another class. Why is this useful?
Think about how sharing common features can save time and effort.
Inheritance helps reuse code by letting a child class use the code of a parent class. This creates a clear relationship and reduces repetition.
What will be the output of this Java code?
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(); } }
Remember that the method called depends on the actual object type, not the reference type.
The object is of type Dog, so Dog's sound() method runs, printing 'Dog barks'. This is called method overriding.
What error will this code produce?
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(); } }
Check if the Child class inherits the show() method without parameters.
Child class inherits show() from Parent. The show(int x) is an overload, not override. Calling c.show() calls Parent's show().
Which option shows the correct way to inherit a class in Java?
Java uses a specific keyword to inherit from a class.
The keyword extends is used to inherit from a class in Java.
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() {}
}Count all methods from class C and its parents.
Class C inherits m1() and m2() from A, m3() from B, and has m4() itself. Total 4 methods.