Unit 3
Q2. Develop a Java program using overriding concept.
(10 Marks)
Definition:
Method Overriding in Java occurs when a subclass (child class) provides a specific
implementation for a method that is already defined in its parent class (superclass).
The method in the subclass must have the same name, return type, and parameters as in
the parent class.
Key Points:
1. It is used to achieve runtime polymorphism.
2. The method in the child class overrides the method in the parent class.
3. The @Override annotation is used to inform the compiler that a method is overridden.
4. The overridden method is called based on the object type, not the reference type.
Rules for Method Overriding:
1. The method must have the same name and same parameters.
2. The return type must be the same or a subclass of the return type declared in the
parent class.
3. The access modifier cannot be more restrictive.
4. Only inherited methods can be overridden.
5. Constructors and static methods cannot be overridden.
Example Program:
// Program to demonstrate Method Overriding
class Animal {
void sound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal a; // Reference variable of parent class
a = new Dog(); // Dog object
[Link](); // Calls Dog's sound()
a = new Cat(); // Cat object
[Link](); // Calls Cat's sound()
}
}
Output:
Dog barks
Cat meows
Explanation:
● The Animal class defines a general method sound().
● The Dog and Cat classes override the sound() method with specific implementations.
● At runtime, the JVM decides which method to call depending on the object type, not the
reference type — this is runtime polymorphism.
Advantages of Method Overriding:
1. Supports runtime polymorphism.
2. Provides flexibility to define specific behavior in subclasses.
3. Promotes code reusability.
4. Makes programs more readable and maintainable.
Q3. Explain about Bubble Sort technique with example.
(10 Marks)
Definition:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent
elements if they are in the wrong order.
This process is repeated until the entire list becomes sorted.
Working Principle:
1. Compare the first two elements of the array.
2. If the first element is greater than the second, swap them.
3. Move to the next pair and continue the comparison.
4. After each pass, the largest element “bubbles up” to the end.
5. Repeat the process for the remaining unsorted elements.
Algorithm:
for i = 0 to n-1
for j = 0 to n-i-1
if (arr[j] > arr[j+1])
swap(arr[j], arr[j+1])
Example:
Consider the array:
[5, 3, 8, 4, 2]
Pass 1: (Compare adjacent elements)
→ [3, 5, 4, 2, 8]
Pass 2:
→ [3, 4, 2, 5, 8]
Pass 3:
→ [3, 2, 4, 5, 8]
✅ Sorted
Pass 4:
→ [2, 3, 4, 5, 8]
Java Program:
// Program to perform Bubble Sort
class BubbleSortExample {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
int n = [Link];
int temp;
// Bubble Sort algorithm
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Display sorted array
[Link]("Sorted Array:");
for (int num : arr) {
[Link](num + " ");
}
}
}
Output:
Sorted Array:
2 3 4 5 8
Time Complexity:
● Best Case: O(n) (when already sorted)
● Average Case: O(n²)
● Worst Case: O(n²)
Space Complexity:
O(1) (in-place sorting algorithm)
Advantages:
1. Simple and easy to understand.
2. Requires only a few lines of code.
3. Works well for small datasets.
Disadvantages:
1. Inefficient for large datasets (O(n²) time).
2. Performs many unnecessary comparisons.
Q4. Discuss about Constructor Method and Inheritance
with Example. (10 Marks)
Definition:
A constructor in Java is a special method that is automatically called when an object is
created.
It is mainly used to initialize objects.
Inheritance is an Object-Oriented Programming (OOP) concept where a class (child or
subclass) inherits properties and methods from another class (parent or superclass).
1. Constructor in Java
Key Points:
● Constructor name must be same as the class name.
● It has no return type, not even void.
● It is invoked automatically at object creation.
● Constructors can be parameterized or non-parameterized.
Syntax:
class ClassName {
ClassName() {
// constructor body
}
}
Types of Constructors:
1. Default Constructor: Provided automatically by Java if no constructor is defined.
2. Parameterized Constructor: Accepts arguments to initialize object values.
3. Copy Constructor: Used to copy data from one object to another (user-defined in
Java).
2. Inheritance in Java
Definition:
Inheritance allows one class to acquire the properties and methods of another class using the
extends keyword.
Syntax:
class Parent {
// parent class code
}
class Child extends Parent {
// child class code
}
Types of Inheritance in Java:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (through Interfaces)
Example Program:
// Program to demonstrate Constructor and Inheritance
class Person {
String name;
int age;
// Parameterized constructor
Person(String n, int a) {
name = n;
age = a;
[Link]("Person constructor called");
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
}
class Student extends Person {
int rollNo;
// Constructor of subclass
Student(String n, int a, int r) {
super(n, a); // Calling parent class constructor
rollNo = r;
[Link]("Student constructor called");
}
void show() {
display();
[Link]("Roll No: " + rollNo);
}
}
public class ConstructorInheritanceDemo {
public static void main(String[] args) {
Student s = new Student("Ram", 20, 101);
[Link]();
}
}
Output:
Person constructor called
Student constructor called
Name: Ram, Age: 20
Roll No: 101
Explanation:
● When the Student object is created, first the parent (Person) constructor executes,
then the child (Student) constructor.
● The super() keyword is used to call the parent class constructor.
● This demonstrates both constructor chaining and inheritance.
Advantages:
1. Constructors help in automatic initialization of objects.
2. Inheritance avoids code duplication.
3. Promotes reusability and modular design.
4. Supports maintainability and readability.
Conclusion:
Constructor and Inheritance are essential OOP features in Java that work together to create
efficient and reusable programs by initializing and extending class functionality.
Q5. Explain about One-Dimensional and Two-Dimensional
Arrays in detail with examples. (10 Marks)
Definition:
An array in Java is a collection of similar data elements stored in a contiguous memory
location.
It allows you to store multiple values of the same data type using a single variable name.
1️⃣ One-Dimensional Array
Definition:
A one-dimensional (1D) array is a list or linear collection of elements that can be accessed
using a single index.
Declaration and Initialization:
Syntax:
datatype arrayName[] = new datatype[size];
Example:
int numbers[] = new int[5]; // Declaration
numbers[0] = 10; // Initialization
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
or
int numbers[] = {10, 20, 30, 40, 50};
Java Program for One-Dimensional Array:
class OneDArrayExample {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
[Link]("Elements of 1D Array:");
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " +
arr[i]);
}
}
}
Output:
Elements of 1D Array:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
2️⃣ Two-Dimensional Array
Definition:
A two-dimensional (2D) array is an array of arrays, often used to represent matrices or
tables.
It stores elements in rows and columns.
Declaration and Initialization:
Syntax:
datatype arrayName[][] = new datatype[rows][columns];
Example:
int matrix[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Java Program for Two-Dimensional Array:
class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
[Link]("Elements of 2D Array (Matrix):");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
}
[Link](); // new line after each row
}
}
}
Output:
Elements of 2D Array (Matrix):
1 2 3
4 5 6
7 8 9
Difference Between 1D and 2D Arrays:
Feature One-Dimensional Array Two-Dimensional Array
Structure Linear Table or Matrix
Syntax int arr[] = new int arr[][] = new
int[5]; int[3][3];
Access Single index Two indices
Use Store list of elements Store tabular data
Advantages of Arrays:
1. Easy to access and manage large amounts of data.
2. Efficient use of memory.
3. Reduces code complexity.
Limitations:
1. Fixed size (cannot be changed after creation).
2. Can store only one data type at a time.
Conclusion:
Arrays in Java provide a systematic way to store and access multiple data values efficiently.
1D arrays represent linear data, while 2D arrays are ideal for tabular data such as matrices.
Q6(a). Explain about Dynamic Method Dispatch. (5 Marks)
Definition:
Dynamic Method Dispatch (also called Runtime Polymorphism) in Java is a mechanism by
which a call to an overridden method is resolved at runtime rather than compile time.
It allows Java to decide which method to execute based on the object type, not the
reference type.
Key Points:
1. It occurs when a superclass reference variable refers to a subclass object.
2. The method that is executed depends on the object being referred to.
3. It supports runtime polymorphism.
4. Implemented using method overriding.
Example Program:
class Animal {
void sound() {
[Link]("Animals make sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
public class DynamicDispatchExample {
public static void main(String[] args) {
Animal a; // reference variable of parent class
a = new Dog(); // Dog object
[Link](); // Calls Dog's method
a = new Cat(); // Cat object
[Link](); // Calls Cat's method
}
}
Output:
Dog barks
Cat meows
Explanation:
● The method sound() is overridden in the Dog and Cat classes.
● The reference type is Animal, but object type changes at runtime.
● Hence, the JVM decides which version of the method to execute during runtime, not
compile time.
Advantages:
● Enables runtime polymorphism.
● Improves code flexibility and reusability.
● Supports object-oriented principles.
Q6(b). Discuss about Implementation of Interface with
Example. (5 Marks)
Definition:
An interface in Java is a blueprint of a class that contains abstract methods (methods
without body).
It is used to achieve abstraction and multiple inheritance.
Key Points:
1. Declared using the keyword interface.
2. Methods are public and abstract by default.
3. Implemented by a class using the implements keyword.
4. A class must provide definitions for all methods declared in the interface.
Syntax:
interface InterfaceName {
void method1();
}
class ClassName implements InterfaceName {
public void method1() {
// method implementation
}
}
Example Program:
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
[Link]("Car starts with key ignition");
}
public void stop() {
[Link]("Car stops when brakes are applied");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Vehicle v = new Car(); // Reference of interface
[Link]();
[Link]();
}
}
Output:
Car starts with key ignition
Car stops when brakes are applied
Explanation:
● The interface Vehicle defines two abstract methods.
● The class Car implements the interface by providing body for both methods.
● The interface reference v points to the Car object, demonstrating abstraction and
polymorphism.
Advantages:
1. Achieves multiple inheritance in Java.
2. Increases code flexibility.
3. Supports abstraction and loose coupling.
4. Makes programs easier to maintain and extend.
Q7. Illustrate Various Types of Inheritance with Example.
(10 Marks)
Definition:
Inheritance is an Object-Oriented Programming (OOP) concept that allows a child class
(subclass) to inherit fields and methods from a parent class (superclass).
It helps in code reusability and makes the code easier to maintain.
Syntax:
class Parent {
// parent class code
}
class Child extends Parent {
// child class inherits Parent class
}
Advantages of Inheritance:
1. Promotes code reusability.
2. Supports method overriding and polymorphism.
3. Reduces code duplication.
4. Improves program structure and readability.
Types of Inheritance in Java:
Type Description
1. Single Inheritance A class inherits from one superclass.
2. Multilevel Inheritance A class inherits from another class, which itself
inherits from another.
3. Hierarchical Inheritance Multiple classes inherit from one parent class.
4. Multiple Inheritance (through A class implements multiple interfaces.
interfaces)
5. Hybrid Inheritance Combination of more than one type (achieved
through interfaces).
1️⃣ Single Inheritance Example
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
public class SingleInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output:
Eating...
Barking...
2️⃣ Multilevel Inheritance Example
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Mammal extends Animal {
void walk() {
[Link]("Walking...");
}
}
class Dog extends Mammal {
void bark() {
[Link]("Barking...");
}
}
public class MultilevelInheritance {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
[Link]();
}
}
Output:
Eating...
Walking...
Barking...
3️⃣ Hierarchical Inheritance Example
class Animal {
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
void bark() {
[Link]("Barking...");
}
}
class Cat extends Animal {
void meow() {
[Link]("Meowing...");
}
}
public class HierarchicalInheritance {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output:
Eating...
Barking...
Eating...
Meowing...
4️⃣ Multiple Inheritance (Using Interfaces)
Java does not support multiple inheritance with classes to avoid ambiguity,
but it can be achieved through interfaces.
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() {
[Link]("From Interface A");
}
public void showB() {
[Link]("From Interface B");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
C obj = new C();
[Link]();
[Link]();
}
}
Output:
From Interface A
From Interface B
Conclusion:
● Single, Multilevel, and Hierarchical inheritance are supported directly by classes.
● Multiple and Hybrid inheritance are implemented using interfaces.
● Inheritance makes Java modular, reusable, and polymorphic.
Q8. Explain about Default Methods in Interface. (10
Marks)
Definition:
In Java 8 and later, default methods were introduced in interfaces.
A default method is a method in an interface that has a method body (implementation).
It allows interfaces to add new methods without breaking existing classes that already
implement the interface.
Syntax:
interface InterfaceName {
default void methodName() {
// method body
}
}
Key Features:
1. Declared using the default keyword.
2. Can have a method body inside an interface.
3. Helps in extending interfaces without affecting existing implementations.
4. Can be overridden by the implementing class.
5. Enables backward compatibility in interfaces.
Example 1: Basic Default Method
interface Vehicle {
void start(); // abstract method
// default method
default void fuelType() {
[Link]("Vehicle uses fuel");
}
}
class Car implements Vehicle {
public void start() {
[Link]("Car starts with key ignition");
}
}
public class DefaultMethodExample {
public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link](); // calling default method
}
}
Output:
Car starts with key ignition
Vehicle uses fuel
Explanation:
● The interface Vehicle contains a default method fuelType().
● The class Car implements Vehicle but doesn’t need to define fuelType(), since it
already has a default implementation.
● Hence, the Car object can directly use it.
Example 2: Overriding Default Method
interface Vehicle {
default void fuelType() {
[Link]("Vehicle uses fuel");
}
}
class ElectricCar implements Vehicle {
@Override
public void fuelType() {
[Link]("ElectricCar uses battery power");
}
}
public class OverrideDefaultMethod {
public static void main(String[] args) {
ElectricCar e = new ElectricCar();
[Link]();
}
}
Output:
ElectricCar uses battery power
Explanation:
● The class ElectricCar overrides the default method fuelType() and provides its
own implementation.
● During runtime, the overridden version from the class is executed.
Advantages of Default Methods:
1. Provides backward compatibility — old classes still work even after new methods are
added to interfaces.
2. Code reusability — same default behavior can be shared by multiple classes.
3. Allows interfaces to evolve without breaking existing code.
4. Supports multiple inheritance of behavior via interfaces.
Conflict Resolution (Multiple Interfaces Case):
If two interfaces have the same default method, the implementing class must override it to
resolve ambiguity.
Example:
interface A {
default void show() {
[Link]("From Interface A");
}
}
interface B {
default void show() {
[Link]("From Interface B");
}
}
class C implements A, B {
public void show() {
[Link]("Resolved in Class C");
}
}
public class MultipleDefaultMethod {
public static void main(String[] args) {
C obj = new C();
[Link]();
}
}
Output:
Resolved in Class C
Conclusion:
Default methods make interfaces more powerful and flexible.
They enable evolution of APIs, reduce code duplication, and enhance reusability while
maintaining backward compatibility.
Q9. Discuss about Multiple Interfaces and Nested
Interfaces with an Example. (10 Marks)
Part A: Multiple Interfaces
Definition:
In Java, multiple interfaces mean that a class can implement more than one interface at the
same time.
This allows multiple inheritance of type, which means a class can inherit behavior from
multiple sources without ambiguity.
Syntax:
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() { ... }
public void methodB() { ... }
}
Key Points:
1. Java does not support multiple inheritance with classes, but it supports it through
interfaces.
2. A class can implement multiple interfaces using commas (,) separated.
3. The class must implement all abstract methods of all interfaces.
4. Helps achieve loose coupling and flexibility.
Example Program (Multiple Interfaces):
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void eat() {
[Link]("Dog eats food");
}
public void play() {
[Link]("Dog loves to play fetch");
}
}
public class MultipleInterfaceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output:
Dog eats food
Dog loves to play fetch
Explanation:
● The class Dog implements two interfaces: Animal and Pet.
● It provides its own definitions for both eat() and play() methods.
● Hence, Dog inherits behavior from both interfaces — demonstrating multiple
inheritance through interfaces.
Part B: Nested Interfaces
Definition:
A nested interface is an interface declared inside another interface or class.
It is used to group related functionalities together logically.
Syntax:
class OuterClass {
interface InnerInterface {
void display();
}
}
Key Points:
1. A nested interface is static by default.
2. Can be declared inside a class or inside another interface.
3. To access it, use the outer name followed by dot (.).
4. Helps organize code logically and avoid naming conflicts.
Example 1: Nested Interface Inside a Class
class Outer {
interface Message {
void greet();
}
}
class Hello implements [Link] {
public void greet() {
[Link]("Hello! This is a nested interface
example.");
}
}
public class NestedInterfaceExample {
public static void main(String[] args) {
[Link] msg = new Hello();
[Link]();
}
}
Output:
Hello! This is a nested interface example.
Example 2: Nested Interface Inside Another Interface
interface OuterInterface {
void outerMethod();
interface InnerInterface {
void innerMethod();
}
}
class Test implements [Link] {
public void innerMethod() {
[Link]("Inner Interface Method Implemented");
}
}
public class NestedInterfaceInsideInterface {
public static void main(String[] args) {
[Link] obj = new Test();
[Link]();
}
}
Output:
Inner Interface Method Implemented
Advantages:
✅ Encourages code organization and modularity.
✅ Supports multiple inheritance through interfaces.
✅ Allows encapsulation of related interfaces.
✅ Avoids naming conflicts in large projects.
Conclusion:
● Multiple interfaces allow a class to implement behavior from more than one source.
● Nested interfaces group related functionalities within classes or interfaces.
Together, they provide flexibility, modularity, and maintainability in Java programs.
Q10. Explain about Inheritance of Interfaces with Syntax
and Example. (10 Marks)
Definition:
In Java, interfaces can inherit from other interfaces using the extends keyword.
This is known as interface inheritance.
When one interface extends another, it inherits all the abstract methods of the parent
interface, and any class that implements the child interface must provide implementations for
all inherited methods.
Key Points:
1. An interface can extend multiple interfaces (unlike classes).
2. A child interface inherits all abstract methods from its parent interfaces.
3. Interfaces use the extends keyword, not implements.
4. Classes implement interfaces, while interfaces extend other interfaces.
5. Promotes multiple inheritance of behavior without ambiguity.
Syntax:
interface ParentInterface1 {
void method1();
}
interface ParentInterface2 {
void method2();
}
interface ChildInterface extends ParentInterface1, ParentInterface2 {
void method3();
}
Then a class can implement the child interface:
class Demo implements ChildInterface {
public void method1() { ... }
public void method2() { ... }
public void method3() { ... }
}
Example Program:
interface Animal {
void eat();
}
interface Pet extends Animal {
void play();
}
class Dog implements Pet {
public void eat() {
[Link]("Dog eats food");
}
public void play() {
[Link]("Dog loves to play with ball");
}
}
public class InterfaceInheritanceExample {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output:
Dog eats food
Dog loves to play with ball
Explanation:
● The Animal interface declares the eat() method.
● The Pet interface extends Animal and adds another method play().
● The Dog class implements the Pet interface, so it must define both methods: eat()
and play().
● Thus, the Dog class inherits methods from both the parent and child interfaces
indirectly.
Example: Multiple Interface Inheritance
interface A {
void showA();
}
interface B {
void showB();
}
// Interface C extends two interfaces
interface C extends A, B {
void showC();
}
class Demo implements C {
public void showA() {
[Link]("From Interface A");
}
public void showB() {
[Link]("From Interface B");
}
public void showC() {
[Link]("From Interface C");
}
}
public class MultipleInterfaceInheritance {
public static void main(String[] args) {
Demo obj = new Demo();
[Link]();
[Link]();
[Link]();
}
}
Output:
From Interface A
From Interface B
From Interface C
Advantages:
✅ Achieves multiple inheritance of behavior without conflicts.
✅ Promotes code reusability and modularity.
✅ Supports hierarchical design of interfaces.
✅ Reduces duplication of method declarations.
Diagram:
[Interface A]
↑
[Interface B]
↑
[Interface C]
↑
[Class Demo]
Conclusion:
Interface inheritance in Java allows one interface to extend another, enabling reusable,
scalable, and organized interface hierarchies.
It helps in building complex, modular applications while maintaining clean and flexible
architecture.