0% found this document useful (0 votes)
10 views

Unit 3 Notes

Introduction to Arrays

Uploaded by

sunhithsirigudi
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)
10 views

Unit 3 Notes

Introduction to Arrays

Uploaded by

sunhithsirigudi
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/ 38

UNIT 3

Syllabus

Arrays: Introduction, Declaration and Initialization of Arrays,


Storage of Array in Computer Memory, Accessing Elements of
Arrays, Operations on Array Elements, Assigning Array to Another
Array, Dynamic Change of Array Size, Sorting of Arrays, Search for
Values in Arrays, Class Arrays, Two-dimensional Arrays, Arrays of
Varying Lengths, Three dimensional Arrays, Arrays as Vectors.

Inheritance: Introduction, Process of Inheritance, Types of


Inheritances, Universal Supe Class-Object Class, Inhibiting
Inheritance of Class Using Final, Access Control and Inheritance,
Multilevel Inheritance, Application of Keyword Super, Constructor
Method and Inheritance, Method Overriding, Dynamic Method
Dispatch, Abstract Classes, Interfaces and Inheritance.

Interfaces: Introduction, Declaration of Interface, Implementation


of Interface, Multiple Interfaces, Nested Interfaces, Inheritance of
Interfaces, Default Methods in Interfaces, Static Methods in
Interface, Functional Interfaces, Annotations
Unit 3
Arrays in Java
1.Introduction to Arrays in Java
An array in Java is a collection of similar types of data stored at contiguous memory
locations. Instead of declaring multiple variables for each data element, arrays allow storing
multiple values in a single variable, making code simpler and more efficient when working
with multiple elements.

Example: If you need to store the marks of five students, you can use an array instead of
five separate variables.

int[] marks = new int[5];

2. Declaration and Initialization of Arrays


In Java, an array must be declared before use, specifying its data type and size. After
declaring, we can initialize the array either at the time of declaration or later.

Syntax for Declaration:

dataType[] arrayName = new dataType[size];

dataType defines the type of elements (e.g., int, double, String).


arrayName is the name of the array.
size is the number of elements the array can hold.

Examples:

1. Declaration with Size:

int[] numbers = new int[5]; // Array of integers with size 5

2. Declaration with Initialization:

int[] numbers = {10, 20, 30, 40, 50}; // Array initialized with values

3. Separate Initialization after Declaration:

Unit : 3 Page : 3. 1
int[] numbers;
numbers = new int[]{1, 2, 3, 4, 5}; // Initializing values separately

3. Storage of Array in Computer Memory


Arrays in Java are stored in contiguous memory locations, meaning each element is stored
in sequence, which allows for efficient indexing and element access. The memory for an
array is allocated in the heap, and the array variable holds the reference to this memory
location.

4. Accessing Elements of Arrays


Each element in an array is accessed using its index. In Java, array indexing starts from 0 ,
so the first element is accessed with arrayName[0] , the second with arrayName[1] , and so
on.

Example Program: Accessing Array Elements

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

// Accessing and printing each element


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + " : " +
numbers[i]);
}
}
}

Output:

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

5. Operations on Array Elements


Basic operations on array elements include reading, modifying, and performing arithmetic
operations.

Example Program: Modifying and Summing Array Elements


Unit : 3 Page : 3. 2
public class ArrayOperations {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

// Modifying array elements


numbers[2] = 35; // Changes the third element to 35

// Summing all elements


int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}

System.out.println("Sum of array elements: " + sum);


}
}

Output:

Sum of array elements: 155

6. Assigning One Array to Another Array


In Java, assigning one array to another does not copy the contents; instead, it copies the
reference. This means both variables will refer to the same array in memory.

Example:

public class ArrayAssignment {


public static void main(String[] args) {
int[] originalArray = {10, 20, 30};
int[] newArray = originalArray; // Assigns the reference, not a
copy

// Modify newArray and observe changes in originalArray


newArray[0] = 99;

System.out.println("Original Array: " + originalArray[0]); //


Output: 99
}
}

If a deep copy (an actual copy of contents) is required, you can manually copy elements or
use the Arrays.copyOf() method.

Unit : 3 Page : 3. 3
Example of Deep Copy:

int[] originalArray = {10, 20, 30};


int[] newArray = java.util.Arrays.copyOf(originalArray,
originalArray.length);

7. Dynamic Change of Array Size


Java arrays have a fixed size after creation. To resize, create a new array with the desired
size, then copy elements from the old array.

Example Program: Dynamic Resizing

public class DynamicArrayResize {


public static void main(String[] args) {
int[] originalArray = {10, 20, 30};

// Create a new array with a larger size


int[] largerArray = new int[5];

// Copy elements to the new array


for (int i = 0; i < originalArray.length; i++) {
largerArray[i] = originalArray[i];
}

largerArray[3] = 40; // Add new element


largerArray[4] = 50;

// Print the new array


for (int num : largerArray) {
System.out.print(num + " ");
}
}
}

Output:

10 20 30 40 50

For dynamic resizing with more flexibility, consider using ArrayList instead of arrays.

8. Sorting of Arrays
The Arrays class in Java provides a convenient sort method to arrange array elements in
ascending order.

Unit : 3 Page : 3. 4
Example Program: Sorting an Array

import java.util.Arrays;

public class ArraySorting {


public static void main(String[] args) {
int[] numbers = {40, 10, 30, 20, 50};

// Sort the array


Arrays.sort(numbers);

// Print the sorted array


System.out.println("Sorted Array: " + Arrays.toString(numbers));
}
}

Output:

Sorted Array: [10, 20, 30, 40, 50]

9. Search for Values in Arrays


The Arrays class provides a binarySearch method to search for an element in a sorted
array. If the array is unsorted, it needs to be sorted first.

Example Program: Searching for an Element

import java.util.Arrays;

public class ArraySearch {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};

int index = Arrays.binarySearch(numbers, 30); // Search for the


value 30

if (index >= 0) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found");
}
}
}

Output:

Unit : 3 Page : 3. 5
Element found at index: 2

10. Arrays Class


The Arrays class in Java (part of java.util package) provides various static methods for
array operations such as sorting, searching, copying, and filling.

Commonly Used Methods:

Arrays.sort(array) - Sorts the array in ascending order.


Arrays.binarySearch(array, value) - Searches for a specified value in a sorted
array.
Arrays.copyOf(array, newLength) - Copies an array to a new array with a specified
length.
Arrays.fill(array, value) - Fills all elements of an array with the specified value.
Arrays.toString(array) - Returns a string representation of the array.

Example of Arrays.fill :

int[] numbers = new int[5];


Arrays.fill(numbers, 100); // Fills all elements with 100
System.out.println(Arrays.toString(numbers)); // Output: [100, 100, 100,
100, 100]

2. Two-Dimensional Array (2D Array)


Definition:

A 2D array is an array of arrays, representing data in a table-like structure with rows


and columns.

Compile-Time Initialization:

The array is initialized at the time of declaration, with predefined rows and columns.

Run-Time Initialization:

The array is created with specified rows and columns, and values are assigned during
execution.

Example:

Unit : 3 Page : 3. 6
public class Main
{
public static void main(String[] args)
{
// Compile-time initialization
int[][] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Run-time initialization
int[][] table = new int[2][3];
table[0][0] = 10;
table[0][1] = 20;
table[0][2] = 30;
table[1][0] = 40;
table[1][1] = 50;
table[1][2] = 60;

// Iteration
System.out.println("Elements in matrix:");
for (int i = 0; i < matrix.length; i++)
{
for (int j = 0; j < matrix[i].length; j++)
{
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}

System.out.println("Elements in table:");
for (int i = 0; i < table.length; i++)
{
for (int j = 0; j < table[i].length; j++)
{
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
}

Explanation:

Compile-time: matrix is initialized with values during declaration.


Run-time: table is created with 2 rows and 3 columns, and values are assigned later.

Unit : 3 Page : 3. 7
Iteration: Nested for loops are used to iterate over rows and columns.

3. Three-Dimensional Array (3D Array)


Definition:

A 3D array is an array of 2D arrays, allowing data storage in a 3-dimensional structure,


often visualized as a collection of matrices (or pages) in a block.

Compile-Time Initialization:

Values are assigned during declaration.

Run-Time Initialization:

The array is defined with specific dimensions, and values are assigned later.

Example:

public class Main


{
public static void main(String[] args)
{
// Compile-time initialization
int[][][] cube =
{
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};

// Run-time initialization
int[][][] box = new int[2][2][3];
box[0][0][0] = 13;
box[0][0][1] = 14;
box[0][0][2] = 15;
box[0][1][0] = 16;
box[0][1][1] = 17;
box[0][1][2] = 18;
box[1][0][0] = 19;
box[1][0][1] = 20;

Unit : 3 Page : 3. 8
box[1][0][2] = 21;
box[1][1][0] = 22;
box[1][1][1] = 23;
box[1][1][2] = 24;

// Iteration
System.out.println("Elements in cube:");
for (int i = 0; i < cube.length; i++)
{
for (int j = 0; j < cube[i].length; j++)
{
for (int k = 0; k < cube[i][j].length; k++)
{
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}

System.out.println("Elements in box:");
for (int i = 0; i < box.length; i++)
{
for (int j = 0; j < box[i].length; j++)
{
for (int k = 0; k < box[i][j].length; k++)
{
System.out.print(box[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Explanation:

Compile-time: cube is initialized during declaration with values.


Run-time: box is created with dimensions [2][2][3], and values are assigned later.
Iteration: Three nested for loops are used to iterate over each dimension of the 3D
array.

4. Matrix Multiplication for 3x3 Matrices


Explanation:
Unit : 3 Page : 3. 9
This program multiplies two 3x3 matrices, A and B , to produce the resulting matrix C .
Each element C[i][j] is calculated as the sum of products of elements in the ith row
of A and the jth column of B .

Program:

public class MatrixMultiplication


{
public static void main(String[] args)
{
// Define two 3x3 matrices
int[][] A = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int[][] B = { {1, 0, 1}, {0, 1, 0}, {1, 0, 1} };

// Result matrix with dimensions 3x3


int[][] C = new int[3][3];

// Matrix multiplication logic


for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
C[i][j] = 0; // Initialize element to 0

for (int k = 0; k < 3; k++)


{
C[i][j] += A[i][k] * B[k][j];
}
}
}

// Display the result matrix


System.out.println("Result of 3x3 Matrix Multiplication:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
System.out.print(C[i][j] + " ");
}
System.out.println();
}
}
}

Matrix Multiplication Logic:


Unit : 3 Page : 3. 10
Three nested for loops iterate over rows, columns, and intermediate elements for
multiplication.
Each element C[i][j] is calculated by summing the product of corresponding
elements in row i of A and column j of B .

for (int i = 0; i < 3; i++)


{
for (int j = 0; j < 3; j++)
{
C[i][j] = 0; // Initialize element to 0

for (int k = 0; k < 3; k++)


{
C[i][j] += A[i][k] * B[k][j];
}
}
}

Expected Output:

Result of 3x3 Matrix Multiplication:


4 2 4
10 5 10
16 8 16

Each element of C is calculated by multiplying and summing the corresponding elements of


matrices A and B . This structured format keeps the program clean and easy to understand.

5. Bubble Sort Program


Explanation:

Bubble Sort repeatedly steps through the array, compares adjacent elements, and
swaps them if they are in the wrong order.
This process continues until the entire array is sorted.

Program:

Unit : 3 Page : 3. 11
public class BubbleSort
{
public static void main(String[] args)
{
int[] arr = {5, 2, 9, 1, 5, 6}; // Array to be sorted
int n = arr.length;

for (int i = 0; i < n - 1; i++)


{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

// Display the sorted array


System.out.println("Sorted Array:");
for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
}
}

Bubble Sort Logic:

The outer loop iterates through the array, with each pass moving the largest unsorted
element to its correct position.
The inner loop compares adjacent elements and swaps them if they are in the wrong
order.

for (int i = 0; i < n - 1; i++)


{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];

Unit : 3 Page : 3. 12
arr[j + 1] = temp;
}
}
}

Expected Output:

Sorted Array:
1 2 5 5 6 9

This Bubble Sort program iterates through the array, performing swaps to arrange the
numbers in ascending order. Each pass ensures that the largest unsorted element "bubbles
up" to its correct position.

6. OOPS Concepts in Java


Object-Oriented Programming (OOP) is a programming paradigm that organizes software
design around data, or objects, rather than functions and logic. An object contains data
(fields or attributes) and code (methods or functions) to manipulate that data. Java is a fully
object-oriented language, meaning almost everything in Java is designed to be part of
objects and classes.

Class : Blue print of an Object


Object: Instance for a class
'Encapsulation: Wrapping data (variables) and methods (functions) into a single unit,
typically a class. This hides the internal state and requires methods to access or modify
data.
Inheritance: Enabling new classes to inherit properties and methods from existing
classes.
Polymorphism: Allowing objects to be treated as instances of their parent class. It
enables methods to do different things based on the object it is acting upon.
Abstraction: Hiding complex implementation details and showing only essential
features.

Unit : 3 Page : 3. 13
Encapsulation
Encapsulation restricts access to certain details of an object, allowing only necessary parts
to be exposed. This is usually achieved by setting fields as private and providing public
getter and setter methods to access or modify the data.

Example Program for Encapsulation:

class Person
{
private String name; // private variable for encapsulation

// Setter method
public void setName(String name)
{
this.name = name;
}

// Getter method
public String getName()
{
return name;
}
}

public class EncapsulationExample


{
public static void main(String[] args)
{
Person person = new Person();
person.setName("Alice"); // Setting name using setter
System.out.println("Name: " + person.getName()); // Getting name
using getter
}
}

Explanation:

Person class has a private variable name , which is encapsulated.


The getName and setName methods provide controlled access to this variable.

Abstraction
Abstraction focuses on exposing only the essential features and hiding the implementation
details. This is usually achieved using abstract classes or interfaces in Java.

Unit : 3 Page : 3. 14
Example Program for Abstraction:

abstract class Animal


{
// Abstract method (no implementation here)
abstract void sound();

// Regular method
public void eat()
{
System.out.println("Animal is eating");
}
}

class Dog extends Animal


{
// Providing implementation of abstract method
public void sound()
{
System.out.println("Dog barks");
}
}

public class AbstractionExample


{
public static void main(String[] args)
{
Animal myDog = new Dog();
myDog.sound(); // Calls the implemented method in Dog
myDog.eat(); // Calls the regular method in Animal
}
}

Explanation:

The Animal class is abstract, containing an abstract method sound and a regular
method eat .
The Dog class extends Animal and provides an implementation for sound .
When we create an instance of Dog , we can call both sound (abstract) and eat
(regular) methods.

Polymorphism
Polymorphism allows methods to perform different tasks based on the object that invokes
them. There are two main types in Java:

Unit : 3 Page : 3. 15
1. Compile-time Polymorphism (Method Overloading)
2. Run-time Polymorphism (Method Overriding)

Compile-time Polymorphism:

Method overloading allows multiple methods with the same name but different parameters in
the same class.

class Calculator
{
public int add(int a, int b)
{
return a + b;
}

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


{
return a + b + c;
}
}

public class CompileTimePolyExample


{
public static void main(String[] args)
{
Calculator calc = new Calculator();
System.out.println("Sum of 2 numbers: " + calc.add(5, 3));
System.out.println("Sum of 3 numbers: " + calc.add(5, 3, 2));
}
}

Explanation:

The Calculator class has two add methods with different parameters, demonstrating
method overloading.

Run-time Polymorphism:

Method overriding allows a subclass to provide a specific implementation of a method


declared in its parent class.

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

Unit : 3 Page : 3. 16
}

class Cat extends Animal


{
// Overriding the sound method
public void sound()
{
System.out.println("Cat meows");
}
}

public class RunTimePolyExample


{
public static void main(String[] args)
{
Animal myAnimal = new Animal();
Animal myCat = new Cat();

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


myCat.sound(); // Calls Cat's overridden sound method
}
}

Explanation:

The Cat class overrides the sound method of Animal .


When we call sound on myCat , it calls the overridden version in Cat , demonstrating
runtime polymorphism.

Inheritance in Java
Inheritance is one of the key features of Object-Oriented Programming (OOP) that allows
one class to inherit properties (Variables) and behaviors (methods) from another class. It
promotes code reusability and establishes a relationship between classes. The base class is
also called as parent class or super class. The derived class is also called as Sub class or
Child class.

Types of Inheritance:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance

Unit : 3 Page : 3. 17
1. Single Inheritance
In single inheritance, a class inherits from only one superclass.

Example 1:

class Animal
{
String name;

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

class Dog extends Animal


{
void bark()
{
System.out.println(name + " is barking");
}
}

class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
d.name = "Buddy";
d.eat(); // Inherited from Animal
d.bark(); // Method of Dog
}
}

Example 2:

class Vehicle
{
int speed;

void start()
{
System.out.println("Vehicle started");
}
}

class Car extends Vehicle

Unit : 3 Page : 3. 18
{
void drive()
{
System.out.println("Car is driving at " + speed + " km/h");
}
}

class Test
{
public static void main(String[] args)
{
Car c = new Car();
c.speed = 60;
c.start(); // Inherited from Vehicle
c.drive(); // Method of Car
}
}

2. Multilevel Inheritance
In multilevel inheritance, a class is derived from a class that is already derived from another
class, creating a chain.

Example 1:

class Animal
{
void sleep()
{
System.out.println("Animal is sleeping");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("Dog is barking");
}
}

class Puppy extends Dog


{
void play()
{
System.out.println("Puppy is playing");

Unit : 3 Page : 3. 19
}
}

class Test
{
public static void main(String[] args)
{
Puppy p = new Puppy();
p.sleep(); // Inherited from Animal
p.bark(); // Inherited from Dog
p.play(); // Method of Puppy
}
}

Example 2:

class Person
{
String name;

void walk()
{
System.out.println(name + " is walking");
}
}

class Employee extends Person


{
int empId;

void work()
{
System.out.println(name + " is working with ID: " + empId);
}
}

class Manager extends Employee


{
void manage()
{
System.out.println(name + " is managing the team");
}
}

class Test
{
public static void main(String[] args)
{
Manager m = new Manager();
Unit : 3 Page : 3. 20
m.name = "John";
m.empId = 1234;
m.walk(); // Inherited from Person
m.work(); // Inherited from Employee
m.manage(); // Method of Manager
}
}

3. Hierarchical Inheritance
In hierarchical inheritance, more than one class inherits from a single superclass.

Example 1:

class Animal
{
void eat()
{
System.out.println("Animal is eating");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("Dog is barking");
}
}

class Cat extends Animal


{
void meow()
{
System.out.println("Cat is meowing");
}
}

class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
d.eat(); // Inherited from Animal
d.bark(); // Method of Dog

Unit : 3 Page : 3. 21
Cat c = new Cat();
c.eat(); // Inherited from Animal
c.meow(); // Method of Cat
}
}

Example 2:

class Shape
{
void draw()
{
System.out.println("Drawing shape");
}
}

class Circle extends Shape


{
void area()
{
System.out.println("Calculating area of circle");
}
}

class Square extends Shape


{
void area()
{
System.out.println("Calculating area of square");
}
}

class Test
{
public static void main(String[] args)
{
Circle cir = new Circle();
cir.draw(); // Inherited from Shape
cir.area(); // Method of Circle

Square sq = new Square();


sq.draw(); // Inherited from Shape
sq.area(); // Method of Square
}
}

Unit : 3 Page : 3. 22
Hybrid Inheritance (Combination of Any 2 Inheritance)
We can simulate hybrid inheritance by combining multiple types of inheritance:

1. Class B inherits from Class A (Single Inheritance).


2. Class C inherits from Class A (Hierarchical Inheritance).
3. Class D inherits from Class B (Multilevel Inheritance).

/
BC
/
D

Example:

class A
{
void methodA()
{
System.out.println("Method A from Class A");
}
}

class B extends A
{
void methodB()
{
System.out.println("Method B from Class B");
}
}

class C extends A
{
void methodC()
{
System.out.println("Method C from Class C");
}
}

class D extends B
{
void methodD()
{
System.out.println("Method D from Class D");
}

Unit : 3 Page : 3. 23
}

class Test
{
public static void main(String[] args)
{
D objD = new D();
objD.methodA(); // Inherited from Class A (Single Inheritance)
objD.methodB(); // Inherited from Class B (Multilevel Inheritance)
objD.methodD(); // Method of Class D

C objC = new C();


objC.methodA(); // Inherited from Class A (Hierarchical
Inheritance)
objC.methodC(); // Method of Class C
}
}

Explanation:
Class A is the parent class and contains methodA() .
Class B extends Class A (Single Inheritance) and adds methodB() .
Class C also extends Class A (Hierarchical Inheritance) and adds methodC() .
Class D extends Class B (Multilevel Inheritance) and adds methodD() .

In this example, Class D inherits properties from Class B (which in turn inherits from Class
A), thus demonstrating multilevel inheritance. Class C independently inherits from Class A,
showcasing hierarchical inheritance.

This combination of multiple types of inheritance allows us to mimic a hybrid inheritance


pattern without using interfaces or multiple inheritance.

Why Multiple Inheritance is not possible in Java?


Java doesn’t support multiple inheritance for classes to avoid the complexity and potential
ambiguity that arises from it. Imagine a situation where two parent classes have a method wi
th the same name -
when a child class inherits from both, which method should it use? This is known as the dia
mond problem

By restricting multiple inheritance, Java ensures that the code remains clear and easy to ma
intain.

Interfaces in Java, however, can be used to achieve a form of multiple inheritance. So while t
he
language itself doesn’t allow it for classes, you still have the flexibility to use multiple interfac
es.
Unit : 3 Page : 3. 24
super Keyword
The super keyword in Java is used within a subclass to refer to members (variables or
methods) of its superclass. It helps:

Call a superclass's constructor.


Access a superclass's method or variable that has been overridden in the subclass.

Example Program for super Keyword:

class Animal
{
String color = "Brown";

public void sound()


{
System.out.println("Animal sound");
}
}

class Dog extends Animal


{
String color = "Black";

public void displayColors()


{
System.out.println("Dog color: " + color); // Refers to
Dog's color
System.out.println("Animal color: " + super.color); // Refers to
Animal's color
}

public void sound()


{
super.sound(); // Calls the superclass (Animal) sound method
System.out.println("Dog barks"); // Adds additional functionality
}
}

public class SuperKeywordExample


{
public static void main(String[] args)
{

Unit : 3 Page : 3. 25
Dog dog = new Dog();
dog.displayColors(); // Display colors from both Dog and Animal
classes
dog.sound(); // Calls overridden method in Dog
}
}

Explanation:

super.color : Accesses the color variable from the superclass Animal .


super.sound() : Calls the sound method from Animal before adding additional
functionality in Dog .

Expected Output:

Dog color: Black


Animal color: Brown
Animal sound
Dog barks

Method Overriding
Method overriding in Java allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. Overriding helps in runtime polymorphism,
enabling behavior specific to the subclass when a superclass reference points to a subclass
object.

Rules for Method Overriding:

The method in the subclass must have the same name, return type, and parameters as
in the superclass.
Only instance methods (non-static) can be overridden.
Access modifiers can be more permissive in the subclass but not more restrictive.

Example Program for Method Overriding:

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

Unit : 3 Page : 3. 26
class Cat extends Animal
{
@Override
public void sound() // Overriding the sound method
{
System.out.println("Cat meows");
}
}

public class MethodOverridingExample


{
public static void main(String[] args)
{
Animal myAnimal = new Animal(); // Calls Animal's sound method
myAnimal.sound();

Animal myCat = new Cat(); // Calls Cat's overridden sound


method
myCat.sound();
}
}

Explanation:

The Cat class overrides the sound method from Animal to provide a specific
implementation.
When myCat.sound() is called, it executes the overridden method in Cat ,
demonstrating polymorphism.

Expected Output:

Animal makes a sound


Cat meows

Here's an overview of abstract classes in Java, covering what they are, why they're used,
and how to implement them with examples.

Abstract Class in Java


1. Introduction to Abstract Classes

Unit : 3 Page : 3. 27
An abstract class in Java is a class that cannot be instantiated directly. It is defined with the
abstract keyword and is meant to be extended by other classes that provide specific
implementations of its methods. Abstract classes can contain both abstract methods
(without a body) and concrete methods (with an implementation).

The main purpose of an abstract class is to serve as a base class from which other classes
inherit. It provides a blueprint for subclasses, defining common attributes and behaviors that
subclasses can either use as-is or override to customize.

Syntax:

abstract class ClassName {


// Abstract and concrete methods
}

Example:

abstract class Shape {


abstract void draw(); // Abstract method with no implementation
}

In this example, Shape is an abstract class with an abstract method draw() . Any class that
extends Shape must provide an implementation for the draw() method.

2. Why Use Abstract Classes?


Abstract classes are useful when:

1. Defining a common structure or template: You want to establish a common structure


for a group of related classes.
2. Providing a base class with some default behavior: You want subclasses to inherit
certain methods as they are, but also allow them to define their own implementations of
specific methods.
3. Encapsulating shared code: Shared attributes and methods can be defined once in
an abstract class, avoiding code duplication across subclasses.

For instance, if you have different shapes (Circle, Rectangle) that share properties like
color and behavior like draw() , you can define these in an abstract class.

3. Example of Abstract Class

Unit : 3 Page : 3. 28
Example of Abstract Class with Abstract and Concrete Methods:

abstract class Animal {


// Abstract method (does not have a body)
abstract void makeSound();

// Concrete method
public void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


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

public class Main {


public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound(); // Calls the Dog's implementation of makeSound()
myDog.eat(); // Calls the eat() method from Animal
}
}

Output:

Dog barks.
This animal eats food.

In this example:

Animal is an abstract class with an abstract method makeSound() and a concrete


method eat() .
Dog extends Animal and provides an implementation for the makeSound() method.
We cannot create an instance of Animal directly, but we can create an instance of
Dog , which inherits both makeSound() and eat() .

4. Key Points to Remember


Cannot be instantiated: You cannot create an instance of an abstract class directly.

Unit : 3 Page : 3. 29
Can contain abstract methods: Abstract classes can have abstract methods, which
subclasses must implement.
Can contain concrete methods: Unlike interfaces, abstract classes can also contain
methods with full implementations.
Can have constructors: Abstract classes can have constructors, which are used when
a subclass is instantiated.
Can have member variables: Abstract classes can declare fields (variables) that can
be inherited by subclasses.

Summary
An abstract class serves as a template for other classes, allowing subclasses to
inherit common functionality while defining their own specific behaviors.
Abstract methods in an abstract class are meant to be implemented by subclasses,
whereas concrete methods can be used as-is.
Abstract classes provide a way to group related classes, sharing common code while
enforcing certain behaviors across subclasses.

This overview should help you understand the basics of abstract classes in Java. Let me
know if you’d like more examples or details on this topic!

Interface in Java
1. Introduction to Interfaces
An interface in Java is a reference type, similar to a class, that contains only abstract
methods (methods without bodies) by default. Interfaces define a contract that classes can
implement, ensuring that they provide specific methods. This helps in achieving abstraction
and multiple inheritance in Java, as classes can implement multiple interfaces but can only
inherit from a single class.

Syntax:

interface InterfaceName
{
// abstract methods
}

Example:

interface Animal
{

Unit : 3 Page : 3. 30
void eat();
void sleep();
}

In this example, any class that implements the Animal interface must define eat and
sleep methods.

2. Declaration of Interface
Interfaces are declared using the interface keyword, and by default, all methods in an
interface are public and abstract. Interfaces can also contain constants (final variables).

Example of Interface Declaration:

interface Vehicle
{
int MAX_SPEED = 120; // Constant
void start(); // Abstract method
void stop();
}

In the Vehicle interface:

MAX_SPEED is a constant variable.


start() and stop() are abstract methods to be implemented by any class that
implements the Vehicle interface.

3. Implementation of Interface
A class implements an interface using the implements keyword. The class must provide
definitions for all the abstract methods declared in the interface.

Example of Interface Implementation:

interface Vehicle
{
void start();
void stop();
}

public class Car implements Vehicle


{

Unit : 3 Page : 3. 31
public void start()
{
System.out.println("Car is starting.");
}

public void stop()


{
System.out.println("Car is stopping.");
}

public static void main(String[] args)


{
Car myCar = new Car();
myCar.start();
myCar.stop();
}
}

Output:

Car is starting.
Car is stopping.

Here, the Car class provides definitions for start() and stop() methods from the
Vehicle interface.

4. Multiple Interfaces
Java does not support multiple inheritance with classes, but a class can implement multiple
interfaces. This allows a class to inherit abstract methods from multiple sources.

Example of Multiple Interfaces:

interface Drivable
{
void drive();
}

interface Flyable
{
void fly();
}

public class FlyingCar implements Drivable, Flyable


{
Unit : 3 Page : 3. 32
public void drive()
{
System.out.println("Driving on the road.");
}

public void fly()


{
System.out.println("Flying in the sky.");
}

public static void main(String[] args)


{
FlyingCar myFlyingCar = new FlyingCar();
myFlyingCar.drive();
myFlyingCar.fly();
}
}

Output:

Driving on the road.


Flying in the sky.

In this example, FlyingCar implements both Drivable and Flyable interfaces, showing
how a class can combine multiple behaviors.

5. Nested Interfaces
A nested interface is an interface declared within another interface or class. It can be
public, private, or protected. Nested interfaces are useful for grouping related interfaces
together and for inner classes.

Example of Nested Interface:

class OuterClass
{
interface InnerInterface
{
void display();
}
}

class Implementer implements OuterClass.InnerInterface


{
public void display()
Unit : 3 Page : 3. 33
{
System.out.println("Displaying from Nested Interface.");
}
}

public class Main


{
public static void main(String[] args)
{
OuterClass.InnerInterface obj = new Implementer();
obj.display();
}
}

Output:

Displaying from Nested Interface.

Here, InnerInterface is a nested interface within OuterClass , and Implementer


implements it.

6. Inheritance of Interfaces
Just like classes, interfaces can inherit other interfaces using the extends keyword. An
interface can extend multiple other interfaces, which allows a combination of multiple
behaviors.

Example of Interface Inheritance:

interface Printable
{
void print();
}

interface Scannable
{
void scan();
}

interface MultifunctionDevice extends Printable, Scannable


{
void copy();
}

class Machine implements MultifunctionDevice


Unit : 3 Page : 3. 34
{
public void print()
{
System.out.println("Printing document.");
}

public void scan()


{
System.out.println("Scanning document.");
}

public void copy()


{
System.out.println("Copying document.");
}
}

public class Main


{
public static void main(String[] args)
{
Machine device = new Machine();
device.print();
device.scan();
device.copy();
}
}

Output:

Printing document.
Scanning document.
Copying document.

Here, MultifunctionDevice inherits from both Printable and Scannable , and Machine
implements all the methods.

7. Default Methods in Interfaces


Java 8 introduced default methods in interfaces, which allow methods to have a default
implementation within an interface. This provides backward compatibility for older
interfaces without breaking existing implementations.

Syntax for Default Method:

Unit : 3 Page : 3. 35
interface InterfaceName
{
default void methodName()
{
// default implementation
}
}

Example:

interface Camera
{
void takePhoto();

default void recordVideo()


{
System.out.println("Recording video in HD.");
}
}

class Smartphone implements Camera


{
public void takePhoto()
{
System.out.println("Taking photo.");
}
}

public class Main


{
public static void main(String[] args)
{
Smartphone myPhone = new Smartphone();
myPhone.takePhoto();
myPhone.recordVideo(); // Calls default method in interface
}
}

Output:

Taking photo.
Recording video in HD.

In this example, recordVideo is a default method in the Camera interface. The Smartphone
class does not override it, so the default implementation is used.

Unit : 3 Page : 3. 36
Unit : 3 Page : 3. 37

You might also like