0% found this document useful (0 votes)
11 views29 pages

FJP Unit 3

The document covers fundamental concepts of Java programming, focusing on arrays, multidimensional arrays, strings, recursion, and wrapper classes. It explains how to declare, instantiate, and initialize arrays, as well as provides examples of using strings and recursive methods. Additionally, it discusses the importance of wrapper classes in Java for converting primitive data types into objects and their applications in collections.

Uploaded by

RAHUL PILLI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

FJP Unit 3

The document covers fundamental concepts of Java programming, focusing on arrays, multidimensional arrays, strings, recursion, and wrapper classes. It explains how to declare, instantiate, and initialize arrays, as well as provides examples of using strings and recursive methods. Additionally, it discusses the importance of wrapper classes in Java for converting primitive data types into objects and their applications in collections.

Uploaded by

RAHUL PILLI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

304185 (C): Fundamentals of JAVA Programming (Elective -I)

Third Year of E & Tc Engineering (2019 Course)


Unit III Methods & Inheritance in JAVA
Arrays:
In Java, an array is a collection of elements of the same type that are stored in a contiguous block
of memory. Arrays are fixed in size, meaning that once they are created, their size cannot be
changed.
Declaring an Array:
An array is declared with the following syntax:

dataType arrayName[];

Instantiating an Array
Once declared, an array must be instantiated (i.e., memory allocated for it):

arrayName = new dataType[size];

Example:
numbers = new int[5];
Declaring and Instantiating in One Step:
You can also declare and instantiate an array in one line:
int[] numbers = new int[5];
Initializing an Array
After declaring and instantiating, you can initialize the array:
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Alternatively, you can use an array initializer:


int[] numbers = {10, 20, 30, 40, 50};

1
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

P1: Write a java program to accept n integer from user into an array and display
them one in each line.
import java.util.Scanner;
public class DisplayArray {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Ask the user for the number of elements (n)
System.out.print("Enter the number of integers you want to store: ");
int n = scanner.nextInt();
// Declare an array to store n integers
int[] numbers = new int[n];
// Accept n integers from the user
System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
// Display the integers, one per line
System.out.println("You entered:");
for (int i = 0; i < n; i++) {
System.out.println(numbers[i]);
}
// Close the scanner
scanner.close();
}
}

2
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Output

Multi-Dimensional Array

Array-Basics in Java Multidimensional Arrays can be defined in simple words as array of


arrays. Data in multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];
where:
 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created. For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.

Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];

3
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];
Size of multidimensional arrays: The total number of elements that can be stored in a
multidimensional array can be calculated by multiplying the size of all the dimensions.
For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.

Application of Multi-Dimensional Array


● Multidimensional arrays are used to store the data in a tabular form. For example, storing the
roll number and marks of a student can be easily done using multidimensional arrays. Another
common usage is to store the images in 3D arrays.
● In dynamic programming questions, multidimensional arrays are used which are used to
represent the states of the problem.
● Apart from these, they also have applications in many standard algorithmic problems
like: Matrix Multiplication, Adjacency matrix representation in graphs, Grid search problems
Two – dimensional Array (2D-Array)
Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional
array can be seen as an array of one – dimensional array for easier understanding.

Indirect Method of Declaration:


 Declaration – Syntax:
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];

 SPPU Exam Code Oct 2023

public class LowerTriangular {


public static void main(String[] args) {
int rows, cols;
// Initialize matrix a
int a[][] = {

4
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

{1, 2, 3},
{8, 6, 4},
{4, 5, 6}
};
// Calculate the number of rows and columns present in the given matrix
rows = a.length;
cols = a[0].length;

// Check if the matrix is square


if (rows != cols) {
System.out.println("Matrix should be a square matrix");
} else {
System.out.println("Lower triangular matrix: ");

// Perform the required operation to convert the given matrix into a lower triangular matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Print element if it's in the lower triangle or on the diagonal, else print 0
if (i >= j) {
System.out.print(a[i][j] + " ");
} else {
System.out.print("0 ");
}
}
System.out.println(); // Move to the next line after each row
}
}
}
}

5
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Java String

Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
How to create a string object?
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the string
already exists in the pool, a reference to the pooled instance is returned. If the string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

2) by new keyword
String s=new String("Welcome");//creates two objects and one reference variable

6
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

No. Method Description

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

static String format(String format,


3 It returns a formatted string.
Object... args)

static String format(Locale l,


4 It returns formatted string with given locale.
String format, Object... args)

5 String substring(int beginIndex) It returns substring for given begin index.

String substring(int beginIndex, int It returns substring for given begin index and end
6
endIndex) index.

It returns true or false after matching the


7 boolean contains(CharSequence s)
sequence of char value.

static String join(CharSequence


8 delimiter, CharSequence... It returns a joined string.
elements)

static String join(CharSequence


9 delimiter, Iterable<? extends It returns a joined string.
CharSequence> elements)

It checks the equality of string with the given


10 boolean equals(Object another)
object.

7
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

No. Method Description

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified string.

It replaces all occurrences of the specified char


13 String replace(char old, char new)
value.

String replace(CharSequence old, It replaces all occurrences of the specified


14
CharSequence new) CharSequence.

static String
15 It compares another string. It doesn't check case.
equalsIgnoreCase(String another)

16 String[] split(String regex) It returns a split string matching regex.

String[] split(String regex, int


17 It returns a split string matching regex and limit.
limit)

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

It returns the specified char value index starting


20 int indexOf(int ch, int fromIndex)
with given index.

21 int indexOf(String substring) It returns the specified substring index.

int indexOf(String substring, int It returns the specified substring index starting
22
fromIndex) with given index.

23 String toLowerCase() It returns a string in lowercase.

8
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

No. Method Description

It returns a string in lowercase using specified


24 String toLowerCase(Locale l)
locale.

25 String toUpperCase() It returns a string in uppercase.

It returns a string in uppercase using specified


26 String toUpperCase(Locale l)
locale.

It removes beginning and ending spaces of this


27 String trim()
string.

It converts given type into string. It is an


28 static String valueOf(int value)
overloaded method.

Example Code:
public class StringExample {
public static void main(String[] args) {
String greeting = "Hello, World!";
// Get length of the string
int length = greeting.length();
System.out.println("Length: " + length);

// Get a character at a specific index


char firstChar = greeting.charAt(0);
System.out.println("First character: " + firstChar);

// Convert to uppercase
String upper = greeting.toUpperCase();
System.out.println("Uppercase: " + upper);

9
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

// Substring from index 7


String sub = greeting.substring(7);
System.out.println("Substring: " + sub);

// Replace 'World' with 'Java'


String replaced = greeting.replace("World", "Java");
System.out.println("Replaced: " + replaced);
}
}

Output:
Length: 13
First character: H
Uppercase: HELLO, WORLD!
Substring: World!
Replaced: Hello, Java!

SPPU Prog. Write a program to join two strings.

public class JoinStrings {


public static void main(String[] args) {
// Declare and initialize two strings
String str1 = "Hello, ";
String str2 = "World!";
// Joining strings using the concat() method
String joinedString1 = str1.concat(str2);
System.out.println("Joined using concat(): " + joinedString1);
// Joining strings using the + operator
String joinedString2 = str1 + str2;
System.out.println("Joined using + operator: " + joinedString2);
}}

10
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Output:
Joined using concat(): Hello, World!
Joined using + operator: Hello, World!

Recursive methods
A recursive method in Java is a method that calls itself in order to solve a problem. Recursion
works by breaking a larger problem into smaller sub-problems of the same type, and it continues
to call itself with smaller inputs until it reaches a base case (a condition where the recursion
stops).
Key Components of Recursion:
 Base Case: The condition under which the recursive calls stop.
 Recursive Case: The part of the function where it calls itself to solve a smaller part of the
problem.
Example: Factorial Calculation Using Recursion
The factorial of a number n is the product of all positive integers less than or equal to n. It can be
defined recursively as:
factorial(n) = n * factorial(n - 1) for n > 1
factorial(1) = 1 (Base Case)
Here’s how you can implement a recursive method to calculate the factorial of a number in Java:
public class RecursiveFactorial {
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: if n is 1, return 1
if (n == 1) {
return 1;
}
// Recursive case: n * factorial of (n-1)
else {
return n * factorial(n - 1);
}
}

11
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

public static void main(String[] args) {


int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}

Output:
Factorial of 5 is: 120

Wrapper class
In Java, wrapper classes are used to convert primitive data types into objects. Each primitive
data type (e.g., int, char, boolean, etc.) has a corresponding wrapper class provided by the Java
API. Wrapper classes are useful when you need an object instead of a primitive data type,
especially when working with data structures like collections that require objects (e.g., ArrayList,
HashMap).
List of Primitive Types and Their Corresponding Wrapper Classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean

12
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Why Use Wrapper Classes?


1. Collections: Data structures like ArrayList, HashMap, etc., require objects, not primitive types.
Wrapper classes allow primitives to be stored in these collections.
2. Null Values: Wrapper classes can store null values, while primitives cannot.
3. Utility Methods: Wrapper classes provide useful methods for converting and manipulating
values, such as converting a string to a number.
4. Autoboxing and Unboxing: Java automatically converts between primitives and their
corresponding wrapper classes, a process known as autoboxing and unboxing.
Example of Autoboxing and Unboxing:
1. Autoboxing: Converting a primitive value to a corresponding wrapper object.
2. Unboxing: Converting a wrapper object back into its corresponding primitive type.
Example of Autoboxing and Unboxing:
import java.util.ArrayList;

public class WrapperExample {


public static void main(String[] args) {
// Autoboxing: Primitive int is automatically converted to Integer object
Integer num = 10; // Equivalent to: Integer num = Integer.valueOf(10);

// Unboxing: Integer object is automatically converted to primitive int


int n = num; // Equivalent to: int n = num.intValue();

// Using wrapper class in a collection (ArrayList requires objects, not primitives)


ArrayList<Integer> list = new ArrayList<>();
list.add(5); // Autoboxing happens here (int is converted to Integer)
list.add(10);

// Iterating through the list and unboxing


for (Integer i : list) {
System.out.println(i); // Unboxing happens here (Integer is converted to int)
}

13
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

}
}

Output:
5
10

Example Program Using Wrapper Classes:


public class WrapperClassExample {
public static void main(String[] args) {
// Creating wrapper objects using valueOf() method
Integer intObj = Integer.valueOf(100);
Double doubleObj = Double.valueOf(3.14);

// Using intValue() and doubleValue() to get the primitive values


int intVal = intObj.intValue();
double doubleVal = doubleObj.doubleValue();

// Displaying the values


System.out.println("Integer Object: " + intObj);
System.out.println("Double Object: " + doubleObj);
System.out.println("Primitive int: " + intVal);
System.out.println("Primitive double: " + doubleVal);

// Autoboxing: Primitive values are automatically converted to wrapper objects


Integer autoBoxedInt = 200;

// Unboxing: Wrapper object is automatically converted to primitive value


int unboxedInt = autoBoxedInt;
System.out.println("Autoboxed Integer: " + autoBoxedInt);
System.out.println("Unboxed Integer: " + unboxedInt);

14
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

}
}

Output:
Integer Object: 100
Double Object: 3.14
Primitive int: 100
Primitive double: 3.14
Autoboxed Integer: 200
Unboxed Integer: 200

Advantages of Wrapper Classes:


1. Enhanced Utility: They provide many useful methods like parseInt(), valueOf(), etc., for easy
data conversion and manipulation.
2. Object-Oriented Features: As objects, wrapper classes can be used in data structures, passed as
parameters, or returned from methods.
3. Autoboxing/Unboxing: Simplifies code by allowing automatic conversion between primitive
types and wrapper objects.
Disadvantages:
1. Memory Overhead: Wrapper objects consume more memory than primitive types.
2. Performance: Manipulating wrapper objects is slower than working with primitive types because
of the overhead of object creation and method calls.

Enumerated data types


In Java, an enumerated type (also known as an enum) is a special data type that allows you to
define a collection of named constants. Enums provide a way to define a set of fixed values that
a variable can hold. They are used when you need a predefined list of values for a variable and
want to prevent assigning any other value outside of this list.
Key Features of Enums:

15
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

1. Type Safety: Enums ensure that a variable can only take one of the predefined constants,
preventing invalid values.
2. Predefined Constants: Enum constants are implicitly public, static, and final. They represent
fixed values and can be compared using ==.
3. Enums Can Have Methods: Unlike simple constants, enums can have fields, methods, and
constructors.
4. Used in Switch Statements: Enums can be used in switch statements to simplify code when
dealing with constant values.

Example of Enum Usage:


public class EnumExample {

// Defining an enum for days of the week


enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY
}

public static void main(String[] args) {


// Assign an enum value to a variable
Day today = Day.WEDNESDAY;

// Using switch statement with enum


switch (today) {
case MONDAY:
System.out.println("Start of the workweek.");
break;
case FRIDAY:
System.out.println("End of the workweek.");
break;
case SATURDAY:

16
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

case SUNDAY:
System.out.println("It's the weekend!");
break;
default:
System.out.println("Midweek day.");
break;
}

// Loop through all values of the enum


for (Day day : Day.values()) {
System.out.println(day);
}
}
}
Output:
Midweek day.
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Explanation:
 The enum Day defines constants for the days of the week.
 In the switch statement, different actions are performed based on the day. Enums can be used in
switch statements for easier comparison.
 The method Day.values() returns an array of all enum constants, which can be looped through.
Advantages of Enums:
 Type safety: Enums provide compile-time type safety, reducing bugs caused by invalid values.

17
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

 Readability: Enums improve code readability by giving meaningful names to fixed sets of
values.
 Easy comparison: Enums can be compared using == since they are constants.

Enum Limitations:
 Enums are not extensible. You cannot add new constants to an enum at runtime.
 All enum constants are public, static, and final, which means they cannot be changed after they are
created.

Command line argument


Command-line arguments in Java allow users to pass information to a program when it is
executed from the command line. These arguments are passed as a string array to the main
method when the program starts. The values of these arguments can be accessed and used inside
the program.
Example of a Java Program Using Command-Line Arguments:
public class CommandLineExample {
public static void main(String[] args) {
// Check if any arguments are passed
if (args.length > 0) {
System.out.println("Command-line arguments are:");

// Loop through and print all arguments


for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments were passed.");
}
}
}
How to Run the Program:

18
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

1. Save the program in a file (e.g., CommandLineExample.java).


2. Compile the program using the javac command:
javac CommandLineExample.java
java CommandLineExample Hello World 123
Output:
Command-line arguments are:
Argument 1: Hello
Argument 2: World
Argument 3: 123

Inheritance in java
Inheritance in Java is one of the core principles of Object-Oriented Programming (OOP). It
allows a new class to inherit the properties and behavior (fields and methods) of an existing
class, promoting code reusability and logical hierarchy.
Key Concepts:
 Super Class (Parent Class): The class whose properties are inherited by another class. It is also called
the base class.
 Sub Class (Child Class): The class that inherits the properties and methods of the superclass. It is also
called the derived class.
 Extends keyword: Used to establish an inheritance relationship between two classes.

Why Use Inheritance?


1. Code Reusability: It allows a class to reuse the properties and methods of another class, reducing
redundancy.
2. Polymorphism: Inheritance facilitates polymorphism, where a subclass can have its own behavior but
can also behave like its superclass.
3. Extensibility: Allows you to add new features to an existing class without modifying the original class.
Types of Inheritance in Java:
1. Single Inheritance: A class inherits from one superclass.
2. Multilevel Inheritance: A class is derived from another derived class.
3. Hierarchical Inheritance: Multiple classes inherit from the same superclass.
Java does not support multiple inheritance directly (a class cannot extend more than one class)
to avoid ambiguity, but this can be achieved through interfaces.

19
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Syntax:
class SuperClass {
// Fields and methods of the superclass
}

class SubClass extends SuperClass {


// Fields and methods of the subclass
}

Example of Single Inheritance:


// Superclass
class Animal {
// Field
String name;

// Method in the superclass


public void eat() {
System.out.println(name + " is eating.");
}
}

// Subclass inheriting Animal


class Dog extends Animal {

// Subclass-specific method
public void bark() {
System.out.println(name + " is barking.");
}

20
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

// Main class to test inheritance


public class InheritanceExample {
public static void main(String[] args) {
// Create an object of the subclass
Dog dog = new Dog();

// Set properties (inherited from Animal)


dog.name = "Buddy";

// Call methods (both inherited and subclass-specific)


dog.eat(); // Inherited method
dog.bark(); // Subclass-specific method
}
}
Output:
Buddy is eating.
Buddy is barking.

Types of Inheritance in Detail:


1. Single Inheritance:
A subclass inherits from a single superclass.
class A { }
class B extends A { } // Single inheritance

21
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

2. Multilevel Inheritance:
In multilevel inheritance, a class is derived from another derived class.
class A { }
class B extends A { }
class C extends B { } // Multilevel inheritance
3. Hierarchical Inheritance:
In hierarchical inheritance, multiple subclasses inherit from a single superclass.
class A { }
class B extends A { }
class C extends A { } // Hierarchical inheritance

Overriding Methods:
A subclass can override a method from its superclass to provide its own implementation. The
overridden method in the subclass must have the same signature (method name and parameters)
as the method in the superclass.
Example:
class Animal {
public void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {


// Overriding the sound method in the subclass
@Override
public void sound() {
System.out.println("Dog barks.");
}
}

public class OverridingExample {

22
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

public static void main(String[] args) {


Dog dog = new Dog();
dog.sound(); // Calls the overridden method in Dog
}
}
Output:
Dog barks.

super Keyword:
The super keyword is used to refer to the immediate superclass object. It can be used to call
superclass methods or constructors.
super.methodName(): Calls a method from the superclass.
super(): Calls the constructor of the superclass.

Example Using super:


class Animal {
public void sound() {
System.out.println("Animal makes a sound.");
}
}

class Dog extends Animal {


@Override
public void sound() {
super.sound(); // Calls the superclass method
System.out.println("Dog barks.");
}
}

public class SuperExample {


public static void main(String[] args) {

23
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

Dog dog = new Dog();


dog.sound();
}
}
Output:
Animal makes a sound.
Dog barks.

Constructor in Inheritance:
When a subclass object is created, the constructor of the superclass is invoked first, followed by
the constructor of the subclass.
If the superclass has a no-argument constructor, it is called automatically. If it has a
parameterized constructor, you must explicitly call it using super().
Example of Constructor Inheritance:
class Animal {
// Parameterized constructor
public Animal(String name) {
System.out.println(name + " is an animal.");
}
}

class Dog extends Animal {


// Constructor of the subclass
public Dog(String name) {
// Call to superclass constructor using super()
super(name);
System.out.println(name + " is a dog.");
}
}

public class ConstructorInheritanceExample {

24
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

public static void main(String[] args) {


Dog dog = new Dog("Buddy");
}
}
Output:
Buddy is an animal.
Buddy is a dog.

Dynamic method dispatch


Dynamic Method Dispatch (also known as runtime polymorphism or method overriding) is
a key feature of object-oriented programming in Java. It refers to the process where a call to an
overridden method is resolved at runtime, rather than compile-time. This allows Java to support
runtime polymorphism, where a superclass reference variable can refer to an object of a subclass
and call the overridden method of that subclass.
Key Concepts of Dynamic Method Dispatch:
1. Method Overriding: When a subclass provides a specific implementation of a method
that is already defined in its superclass.
2. Super Class Reference, Subclass Object: Dynamic method dispatch occurs when a
superclass reference variable refers to an object of a subclass. The overridden method of
the subclass is called, even though the reference is of the superclass type.
3. Runtime Polymorphism: The exact method to be invoked is determined at runtime,
based on the object being referred to by the superclass reference.

Example of Dynamic Method Dispatch:


// Superclass
class Animal {
// Overridden method
public void sound() {
System.out.println("Animal makes a sound");
}
}

25
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

// Subclass 1
class Dog extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println("Dog barks");
}
}

// Subclass 2
class Cat extends Animal {
// Overriding the sound method
@Override
public void sound() {
System.out.println("Cat meows");
}
}

public class DynamicDispatchExample {


public static void main(String[] args) {
// Superclass reference variable
Animal animal;

// Refer to a Dog object


animal = new Dog();
animal.sound(); // Calls Dog's sound method

// Refer to a Cat object


animal = new Cat();
animal.sound(); // Calls Cat's sound method

26
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

}
}
Output:
Dog barks
Cat meows

Polymorphism
Polymorphism in Java is a key concept of object-oriented programming (OOP) that allows
objects of different classes to be treated as objects of a common super class. It refers to the
ability of a single interface or method to represent different underlying forms (data types or
objects). Polymorphism helps in making programs more flexible and reusable.
There are two types of polymorphism in Java:
1. Compile-time Polymorphism (Method Overloading)
 Method Overloading is when multiple methods have the same name but differ in the
number or type of parameters. The correct method is determined at compile-time based
on the method signature.
Example
class MathOperation {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}

27
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

public class Main {


public static void main(String[] args) {
MathOperation math = new MathOperation();
System.out.println(math.add(5, 10)); // Calls first add() method
System.out.println(math.add(5.5, 10.5)); // Calls second add() method
System.out.println(math.add(5, 10, 15)); // Calls third add() method
}
}

2. Run-time Polymorphism (Method Overriding)


 Method Overriding happens when a subclass provides a specific implementation of a
method already defined in its parent class. The call to the overridden method is resolved
at runtime.
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");

28
Prepared By: Prof. Shivam Agrawal
304185 (C): Fundamentals of JAVA Programming (Elective -I)

}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal reference, Animal object
Animal myDog = new Dog(); // Animal reference, Dog object
Animal myCat = new Cat(); // Animal reference, Cat object

myAnimal.sound(); // Calls Animal's sound method


myDog.sound(); // Calls Dog's sound method
myCat.sound(); // Calls Cat's sound method
}
}
In the example above, the sound() method behaves differently depending on the object (whether
it’s a Dog or a Cat) due to runtime polymorphism.
Advantages of Polymorphism:
 Flexibility: Polymorphism allows code to be more flexible and reusable, making it easier
to scale.
 Extensibility: New functionalities can be introduced with less modification to the
existing code.
 Maintainability: It makes code easier to maintain because the same method name can
work on different types of objects.

29
Prepared By: Prof. Shivam Agrawal

You might also like