Unit - II: Inheritance, Interface and Packages (12 Marks)
Inheritance
1. Define Inheritance and List its types:
Inheritance is a mechanism wherein a new class is derived from an existing class. Types:
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
- Hybrid Inheritance (via Interfaces)
2. State the use of final keyword with respect to inheritance:
The 'final' keyword prevents further inheritance. A final class cannot be extended, and a final method
cannot be overridden.
3. Program to Demonstrate Multilevel Inheritance:
class A {
void displayA() { System.out.println("Class A"); }
class B extends A {
void displayB() { System.out.println("Class B"); }
class C extends B {
void displayC() { System.out.println("Class C"); }
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.displayA(); obj.displayB(); obj.displayC();
}
4. Explain Single and Multilevel Inheritance with example:
Single: One class inherits from another.
Multilevel: A class inherits from a derived class.
5. Program for class Book and BookInfo:
class Book {
String author, title; double price;
Book(String a, String t, double p) {
author = a; title = t; price = p;
class BookInfo extends Book {
int stock;
BookInfo(String a, String t, double p, int s) {
super(a, t, p); stock = s;
void display() {
System.out.println(title + " by " + author + ", Rs." + price + ", Stock: " + stock);
6. Program for Hierarchical Inheritance:
class A { void msg() { System.out.println("A"); } }
class B extends A { void msgB() { System.out.println("B"); } }
class C extends A { void msgC() { System.out.println("C"); } }
7. Method Overriding Example:
class Parent { void show() { System.out.println("Parent"); } }
class Child extends Parent { void show() { System.out.println("Child"); } }
8. Constructor Overloading Example:
class Demo {
Demo() { }
Demo(int x) { System.out.println(x); }
9. Use of super keyword:
- Call parent class constructor
- Access parent class methods/variables
10. Dynamic Method Dispatch:
Parent obj = new Child(); obj.show();
Method of the actual object (Child) is called at runtime.