0% found this document useful (0 votes)
23 views33 pages

Arrays Unit 3

Uploaded by

akramshaik2004
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)
23 views33 pages

Arrays Unit 3

Uploaded by

akramshaik2004
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/ 33

UNIT -3

Arrays
An array is a collection of similar types of data.
For example, if we want to store the names of 100 people then we can create an array of the string
type that can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java array is
always fixed.

How to declare an array in Java?


In Java, here is how we can declare an array.
dataType[] arrayName;
• dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
• arrayName - it is an identifier
For example,
double[] data;
Here, data is an array that can hold values of type double.
To define the number of elements that an array can hold, we have to allocate memory for the array
in Java. For example,
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or length of the array is 10.
In Java, we can declare and allocate the memory of an array in one single statement. For example,
double[] data = new double[10];

How to Initialize Arrays in Java?


In Java, we can initialize arrays during declaration. For example,
//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};
Here, we have created an array named age and initialized it with the values inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java compiler automatically
specifies the size by counting the number of elements in the array (i.e. 5).
UNIT -3
In the Java array, each memory location is associated with a number. The number is known as an
array index. We can also initialize arrays in Java, using the index number. For example,
// declare an array
int[] age = new int[5];
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;

..
Java Arrays initialization
Note:
• Array indices always start from 0. That is, the first element of an array is at index 0.
• If the size of an array is n, then the last element of the array will be at index n-1.

How to Access Elements of an Array in Java?


We can access the element of an array using the index number. Here is the syntax for accessing
elements of an array,
// access array elements
array[index]
Let's see an example of accessing array elements using index numbers.
Example: Access Array Elements
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
UNIT -3
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
In the above example, notice that we are using the index number to access each element of the array.
We can use loops to access all the elements of the array at once.

Looping Through Array Elements


In Java, we can also loop through each element of the array. For example,
Example: Using For Loop
class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5};

// loop through the array


// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}
}
UNIT -3
Output
Using for Loop:
12
4
5
In the above example, we are using the for Loop in Java to iterate through each element of the array.
Notice the expression inside the loop,
age.length
Here, we are using the length property of the array to get the size of the array.
Operations on array elements
Example :
public class ArrayOperations {
public static void main(String[] args) {
// 1. Declare and Initialize an Array
int[] arr = {10, 20, 30, 40, 50};
// 2. Access Elements
System.out.println("First element: " + arr[0]); // Access the first element
// 3. Modify an Element
arr[2] = 35; // Change the third element
System.out.println("Updated third element: " + arr[2]);
// 4. Iterate and Print All Elements
System.out.println("All elements in the array:");
for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " + arr[i]);
}
// 5. Find the Sum of All Elements
int sum = 0;
for (int num : arr) {
sum += num;
}
System.out.println("Sum of all elements: " + sum);
UNIT -3
// 6. Find the Maximum Element
int max = arr[0];
for (int num : arr) {
if (num > max) {
max = num;
}
}
System.out.println("Maximum element: " + max);
// 7. Sort the Array
java.util.Arrays.sort(arr);
System.out.println("Array after sorting: " + java.util.Arrays.toString(arr));
}
}
Assigning array to another array
In Java, assigning one array to another doesn't create a new array; it creates a reference to the same
array. If you want to create a copy of the array, you need to explicitly copy the elements. Here's a
detailed explanation:
1. Assigning One Array to Another (Reference Assignment)
When you assign one array to another, both references point to the same array in memory. Changes
to one array reflect in the other.
Example :
int[] originalArray = {1, 2, 3, 4};
int[] newArray = originalArray;
// Modifying newArray
newArray[0] = 99;
// Both arrays now reflect the change
System.out.println("Original Array: " + java.util.Arrays.toString(originalArray)); // [99, 2, 3, 4]
System.out.println("New Array: " + java.util.Arrays.toString(newArray)); // [99, 2, 3, 4]
UNIT -3
2. Creating a Copy of an Array
If you want to create a separate array with the same elements, use one of the following methods:
a. Using Arrays.copyOf
int[] originalArray = {1, 2, 3, 4};
int[] copiedArray = java.util.Arrays.copyOf(originalArray, originalArray.length);
// Modifying copiedArray
copiedArray[0] = 99;
// Original array remains unchanged
System.out.println("Original Array: " + java.util.Arrays.toString(originalArray)); // [1, 2, 3, 4]
System.out.println("Copied Array: " + java.util.Arrays.toString(copiedArray)); // [99, 2, 3, 4]
Dynamic change of array size
In Java, arrays have a fixed size, meaning once you create an array, its size cannot be changed.
However, you can achieve dynamic behavior using the following approaches:
1. Using ArrayList (Recommended for Dynamic Arrays)
An ArrayList is part of Java's java.util package and allows dynamic resizing.
Example :
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<Integer> list = new ArrayList<>();
// Add elements
list.add(10);
list.add(20);
list.add(30);
// Display the list
System.out.println("ArrayList: " + list); // Output: [10, 20, 30]
// Remove an element
list.remove(1); // Removes the element at index 1
System.out.println("After removal: " + list); // Output: [10, 30]
// Add more elements dynamically
list.add(40);
UNIT -3
list.add(50);
System.out.println("After adding more elements: " + list); // Output: [10, 30, 40, 50]
}
}
Sorting of arrays
Sorting arrays in Java can be done in several ways depending on the type of data (primitive types or
objects) and the desired sorting order (ascending or descending). Here's a guide to sorting arrays:
1. Sorting Primitive Arrays
The Arrays.sort() method is used for sorting primitive data types (like int, double, etc.) in ascending
order.
Example:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] numbers = {5, 3, 8, 1, 2};
// Sorting in ascending order
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers)); // Output: [1, 2, 3, 5, 8]
}
}

2. Sorting Object Arrays


For object arrays (like String or custom objects), Arrays.sort() also works, as long as the elements
are Comparable.
Example (Strings):
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = {"Charlie", "Alice", "Bob"};
// Sorting in ascending order (alphabetical)
Arrays.sort(names);
UNIT -3
System.out.println("Sorted array: " + Arrays.toString(names)); // Output: [Alice, Bob, Charlie]
}
}
Two-dimensional arrays
Two-dimensional arrays in Java are arrays of arrays, often referred to as matrix-like structures.
They are used to store data in rows and columns, making them ideal for representing grids, tables,
and matrices.
1. Declaration and Initialization
a. Declaration
int[][] array;
b. Initialization
You can initialize a 2D array with:
1. Fixed Size:
int[][] array = new int[rows][columns];
Example:
int[][] array = new int[3][2]; // 3 rows and 2 columns
2.With Values:
int[][] array = {
{1, 2},
{3, 4},
{5, 6}
};

2. Accessing Elements
To access or modify an element, use the row and column indices:
array[row][column] = value;
int value = array[row][column];
Example:
public class Main {
public static void main(String[] args) {
int[][] array = {
{1, 2},
UNIT -3
{3, 4},
{5, 6}
};

// Access and print the element at row 1, column 1


System.out.println(array[1][1]); // Output: 4

// Modify the element at row 2, column 0


array[2][0] = 10;
System.out.println(array[2][0]); // Output: 10
}
}
Three dimensional array
A three-dimensional array in Java is an array of arrays of arrays. It can be visualized as a cube or a
collection of 2D arrays. This type of array is useful when you need to represent data in three
dimensions, such as in a 3D grid or a data cube.
1. Declaration and Initialization
a. Declaration
int[ ][ ][ ] array;
b. Initialization
1.Fixed Size:
int[ ][ ][ ] array = new int[depth][rows][columns];
Example:
int[ ][ ][ ] array = new int[2][3][4]; // 2 blocks, each with 3 rows and 4 columns
2.With Values:
int[ ][ ][ ] array = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
UNIT -3
{10, 11, 12}
}
};

2. Accessing Elements
To access or modify an element, specify the indices for depth, row, and column:
array[depth][row][column] = value;
int value = array[depth][row][column];
Example:
public class Main {
public static void main(String[] args) {
int[ ][ ][ ] array = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};

// Access and print an element


System.out.println(array[1][0][2]); // Output: 9

// Modify an element
array[0][1][2] = 99;
System.out.println(array[0][1][2]); // Output: 99
}
}
UNIT -3
Java ArrayList
In Java, we use the ArrayList class to implement the functionality of resizable-arrays.
It implements the List interface of the collections framework .

Java ArrayList Implementation

Java ArrayList Vs Array


In Java, we need to declare the size of an array before we can use it. Once the size of an array is
declared, it's hard to change it.
To handle this issue, we can use the ArrayList class. It allows us to create resizable arrays.
Unlike arrays, arraylists can automatically adjust their capacity when we add or remove elements
from them. Hence, arraylists are also known as dynamic arrays.

Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we can
create arraylists in Java:
ArrayList<Type> arrayList= new ArrayList<>();
Here, Type indicates the type of an arraylist. For example,
// create Integer type arraylist
ArrayList<Integer> arrayList = new ArrayList<>();

// create String type arraylist


ArrayList<String> arrayList = new ArrayList<>();
In the above program, we have used Integer not int. It is because we cannot use primitive types
while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
UNIT -3
Here, Integer is the corresponding wrapper class of int. To learn more, visit the Java wrapper class.

Example: Create ArrayList in Java


import java.util.ArrayList;
class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();
// Add elements to ArrayList
languages.add("Java");
languages.add("Python");
languages.add("Swift");
System.out.println("ArrayList: " + languages);
}
}

Output
ArrayList: [Java, Python, Swift]
In the above example, we have created an ArrayList named languages.
Here, we have used the add() method to add elements to the arraylist. We will learn more about
the add() method later in this tutorial.

Basic Operations on ArrayList


The ArrayList class provides various methods to perform different operations on arraylists. We will
look at some commonly used arraylist operations in this tutorial:
• Add elements
• Access elements
• Change elements
• Remove elements
UNIT -3
1. Add Elements to an ArrayList
To add a single element to the arraylist, we use the add() method of the ArrayList class. For
example,
import java.util.ArrayList;

class Main {
public static void main(String[] args){
// create ArrayList
ArrayList<String> languages = new ArrayList<>();

// add() method without the index parameter


languages.add("Java");

languages.add("C");
languages.add("Python");
System.out.println("ArrayList: " + languages);
}
}
Output
ArrayList: [Java, C, Python]
In the above example, we have created an ArrayList named languages. Here, we have used
the add() method to add elements to languages.
2. Access ArrayList Elements
To access an element from the arraylist, we use the get() method of the ArrayList class. For
example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// add elements in the arraylist
animals.add("Cat");
animals.add("Dog");
UNIT -3
animals.add("Cow");
System.out.println("ArrayList: " + animals);

// get the element from the arraylist


String str = animals.get(1);

System.out.print("Element at index 1: " + str);


}
}
Output
ArrayList: [Cat, Dog, Cow]
Element at index 1: Dog
In the above example, we have used the get() method with parameter 1. Here, the method returns
the element at index 1.
To learn more, visit the Java ArrayList get().
We can also access elements of the ArrayList using the iterator() method. To learn more, visit Java
ArrayList iterator().

3. Change ArrayList Elements


To change elements of the arraylist, we use the set() method of the ArrayList class. For example,
import java.util.ArrayList;

class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();

// add elements in the array list


languages.add("Java");
languages.add("Kotlin");
languages.add("C++");
System.out.println("ArrayList: " + languages);
UNIT -3
// change the element of the array list
languages.set(2, "JavaScript");

System.out.println("Modified ArrayList: " + languages);


}
Output
ArrayList: [Java, Kotlin, C++]
Modified ArrayList: [Java, Kotlin, JavaScript]
In the above example, we have created an ArrayList named languages. Notice the line,
language.set(2, "JavaScript");
Here, the set() method changes the element at index 2 to JavaScript.
To learn more, visit the Java ArrayList set().

4. Remove ArrayList Elements


To remove an element from the arraylist, we can use the remove() method of the ArrayList class.
For example,
import java.util.ArrayList;

class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();

// add elements in the array list


animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
System.out.println("ArrayList: " + animals);
// remove element from index 2
String str = animals.remove(2);
System.out.println("Updated ArrayList: " + animals);
System.out.println("Removed Element: " + str);
}
UNIT -3
}
Output
ArrayList: [Dog, Cat, Horse]
Updated ArrayList: [Dog, Cat]
Removed Element: Horse
Here, the remove() method takes the index number as the parameter. And, removes the element
specified by the index number.
To learn more, visit the Java ArrayList remove().
We can also remove all the elements from the arraylist at once. To learn more, visit
• Java ArrayList removeAll()
• Java ArrayList clear()
Java Vector
The Vector class is an implementation of the List interface that allows us to create resizable-arrays
similar to the ArrayList class.
Java Vector vs. ArrayList
In Java, both ArrayList and Vector implements the List interface and provides the same
functionalities. However, there exist some differences between them.
The Vector class synchronizes each individual operation. This means whenever we want to perform
some operation on vectors, the Vector class automatically applies a lock to that operation.
It is because when one thread is accessing a vector, and at the same time another thread tries to
access it, an exception called ConcurrentModificationException is generated. Hence, this
continuous use of lock for each operation makes vectors less efficient.
However, in array lists, methods are not synchronized. Instead, it uses
the Collections.synchronizedList() method that synchronizes the list as a whole.
Note: It is recommended to use ArrayList in place of Vector because vectors less efficient.
Creating a Vector
Here is how we can create vectors in Java.
Vector<Type> vector = new Vector<>();
Here, Type indicates the type of a linked list. For example,
// create Integer type linked list
Vector<Integer> vector= new Vector<>();
// create String type linked list
Vector<String> vector= new Vector<>();
UNIT -3
Methods of Vector
The Vector class also provides the resizable-array implementations of the List interface (similar to
the ArrayList class). Some of the Vector methods are:
Add Elements to Vector
• add(element) - adds an element to vectors
• add(index, element) - adds an element to the specified position
• addAll(vector) - adds all elements of a vector to another vector
For example,
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();

// Using the add() method


mammals.add("Dog");
mammals.add("Horse");

// Using index number


mammals.add(2, "Cat");
System.out.println("Vector: " + mammals);

// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");

animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
UNIT -3
Output
Vector: [Dog, Horse, Cat]
New Vector: [Crocodile, Dog, Horse, Cat]
Access Vector Elements
• get(index) - returns an element specified by the index
• iterator() - returns an iterator object to sequentially access vector elements
For example,
import java.util.Iterator;
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);
// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}

Output
Element at index 2: Cat
Vector: Dog, Horse, Cat,
UNIT -3

Remove Vector Elements


• remove(index) - removes an element from specified position
• removeAll() - removes all the elements
• clear() - removes all elements. It is more efficient than removeAll()
For example,
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");

System.out.println("Initial Vector: " + animals);

// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);

// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output
Initial Vector: [Dog, Horse, Cat]
Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []
UNIT -3
Inheritance
Inheritance is a mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class.
Inheritance creates a new class from an existing class. Any new class that we create from an existing
class is called a derived class, and an existing class is called a base class.
Concept and Types of inheritance
The inheritance relationship enables a derived class to inherit features from its base class. A derived
class can add new features of its own. Therefore rather than creating completely new classes from
scratch, we can take advantage of inheritance and reduce software complexity.
• Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class that inherits the other class. It is also called a
derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism that facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.
Types of inheritance :
• Single Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance

Syntax
UNIT -3
class XYZ extends ABC
{
// block of code
}

1. Single Inheritance
It is the inheritance hierarchy wherein one derived class inherits from one base class.
Ex :
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}
Output :
I am green!
I am a Bird

2. Multiple Inheritance
UNIT -3
It is the inheritance hierarchy wherein one derived class inherits from multiple base classes.
Example :
class A {
void testMethod() {
System.out.println("I am from class A");
}
}
class B {
void testMethod() {
System.out.println("I am from class B");
}
}
// Not possible to inherit classes this way, But for understanding, let us suppose
class C extends A, B {
void newMethod() {
System.out.println("I am from subclass");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
obj.testMethod();
// Ambiguity here as it's present in both A and B class
}
}

3. Hierarchical Inheritance
It is the inheritance hierarchy wherein multiple derived classes inherit from one base class.

class Bird {
UNIT -3
void fly() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
System.out.println("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.whatColourAmI();
par.fly();

//Call methods of Crow Class


cro.whatColourAmI();
cro.fly();
}
}
Output :
I am green!
I am a Bird
I am black!
UNIT -3
I am a Bird

4. Multilevel Inheritance
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.

class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
System.out.println("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
obj.whatCanISing();
obj.whatColourAmI();
obj.fly();
}
}
Output :
UNIT -3
I can sing Opera!
I am green!
I am a Bird
5. Hybrid Inheritance
It is the inheritance hierarchy that reflects any legal combination of the other four types of
inheritance
Dynamic Method Dispatch in Java
Dynamic Method Dispatch in Java is the process by which a call to an overridden method is
resolved at runtime (during the code execution). The concept of method overriding is the way to
attain runtime polymorphism in Java. During the code execution, JVM decides which
implementation of the same method should be called.
What is Runtime Polymorphism in Java?
Dynamic Method Dispatch is another name for Runtime polymorphism in Java which originates
with the concept of method overriding. In this case, the call to an overridden method will be
resolved at the time of code execution (runtime) rather than the compile time.
The basis of dynamic method dispatch in Java starts with Inheritance where two or more classes
exhibit a parent-child relationship. Now, there might be several versions of the same method in the
parent as well as child classes or you can also call them superclass and subclasses.
It seems puzzling as to which version of the same method will be called. However, Java Virtual
Machine (JVM) easily perceives the same during runtime based on the type of object being
referred to.

In Java, the object creation occurs in part 2 with the new operator assigned to any class which
denotes the type of object that will be created, and part 1 represents the reference variable. In the
figure given above, the object created will be an instance of class A.
But remember that runtime polymorphism depends on the type of object being created (as in part 2)
and not the reference variable (part 1).
UNIT -3
When different classes that follow inheritance have the same method with the same name,
parameters, and/or return type, it is known as method overriding.

Here, the reference variable is referring to the object of class B. The reference variable belongs to
the superclass or parent class while the object is made up of the subclass or child class. It is also
known as upcasting.
The subclasses exhibit an IS-A relationship with the parent class. For example, there can be a class
MobileOS. Since both Android as well as iOS are mobile operating systems, they are the subclasses
of MobileOS. So in terms of the IS-A relationship, we can say that Android "IS A" MobileOS and
iOS "IS A" MobileOS.
The concept of upcasting can be seen in this example. Whether we create the object
of Android or iOS, the reference variable is of the superclass in both cases, i.e., MobileOS.
Method Overriding
As mentioned earlier, when you can find the same method with the same signature (method name,
parameters, and return type) in inherited classes, it leads to method overriding. The
implementation of the class, i.e., the body of the class might differ in the overridden methods.
Therefore, the inherited classes having the same method with varied implementations make up an
example of runtime polymorphism.
Advantages
• Runtime polymorphism in Java allows the superclass to define as well as share its own
method and also allows the sub-classes to define their own implementation.
• The subclasses have the privilege to use the same method as their parent or define their
specific implementation for the same method wherever necessary. Therefore, in one way, it
supports code reusability when using the same method and implementation.
• It allows method overriding which is the basis for runtime polymorphism in Java.
UNIT -3
Example of Java Runtime Polymorphism
Here, we'll consider the same example that has been described above.
import java.io.*;
//Creating a parent class
class MobileOS
//virtual method
void display()
{
System.out.println("We are talking about mobile operating systems.");
}
}

//Creating a child class for parent 'MobileOS'


class Android extends MobileOS{

//overriding display method


void display()
{
System.out.println("Android is a MobileOS.");
}
}

//Creating a child class for parent 'MobileOS'


class iOS extends MobileOS{

//overriding display method


void display()
{
System.out.println("iOS is a MobileOS.");
}
}
UNIT -3

//Main class
class Main {
//calling main method
public static void main (String[] args) {

//Create an object of parent class


MobileOS os = new MobileOS();
os.display();

//Create an object of child class


os=new Android(); //Upcasting
os.display();

//Create an object of child class


os=new iOS(); //Upcasting
os.display();
}
}
Output:
We are talking about mobile operating systems.
Android is a MobileOS.
iOS is a MobileOS.
Java Abstract Class and Abstract Methods
Java Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes). We
use the abstract keyword to declare an abstract class. For example,
// create an abstract class
abstract class Language {
// fields and methods
}
...
UNIT -3

// try to create an object Language


// throws an error
Language obj = new Language();
An abstract class can have both the regular methods and abstract methods. For example,
abstract class Language {
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
To know about the non-abstract methods, visit Java methods. Here, we will learn about abstract
methods.

Java Abstract Method


A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,
abstract void display();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract. Otherwise, it will
generate an error. For example,
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
}

Example: Java Abstract Class and Method


Though abstract classes cannot be instantiated, we can create subclasses from it. We can then access
members of the abstract class using the object of the subclass. For example,
UNIT -3

abstract class Language {

// method of abstract class


public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}
Output
This is Java programming
In the above example, we have created an abstract class named Language. The class contains a
regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the abstract class using
the object obj.
UNIT -3

Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in
Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
o Java Interface also represents the IS-A relationship.
o It cannot be instantiated just like the abstract class.
o Since Java 8, we can have default and static methods in an interface.
o Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Example:
interface Animal {
void eat();
void sleep();
UNIT -3
}
In this example, the Animal interface declares two method signatures: eat() and sleep(). Any class
implementing the Animal interface must provide concrete implementations for these methods.
Java Interface Example
In this example, the Printable interface has only one method, and its implementation is provided in
the A6 class.
File Name: InterfaceExample.java
interface printable{
void print();
}
class InterfaceExample implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
InterfaceExample obj = new InterfaceExample();
obj.print();
}
}
Output :
Hello
Multiple Inheritance using Interfaces
In Java, multiple inheritance is not supported directly with classes (i.e., a class cannot inherit from
more than one class). However, you can achieve multiple inheritance using interfaces. A class can
implement multiple interfaces, which allows it to inherit behavior from more than one source.
Simple Example of Multiple Inheritance Using Interfaces:
// Interface 1
interface Animal {
void sound(); // Abstract method
}

// Interface 2
interface Mammal {
void walk(); // Abstract method
}
UNIT -3

// Concrete class implementing both interfaces


class Dog implements Animal, Mammal {
// Implementing the sound method from Animal
public void sound() {
System.out.println("Woof");
}

// Implementing the walk method from Mammal


public void walk() {
System.out.println("Dog is walking");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Woof
dog.walk(); // Output: Dog is walking
}
}

You might also like