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

java

The document covers various topics in Java programming, including arrays, inheritance, interfaces, method overriding, abstract classes, and dynamic method dispatch. It includes programming exercises and explanations on how to implement these concepts, such as finding the greatest number in an array, sorting arrays, performing matrix multiplication, and illustrating the use of two-dimensional and three-dimensional arrays. Each section provides both theoretical explanations and practical Java code examples.

Uploaded by

nikhilaeede
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java

The document covers various topics in Java programming, including arrays, inheritance, interfaces, method overriding, abstract classes, and dynamic method dispatch. It includes programming exercises and explanations on how to implement these concepts, such as finding the greatest number in an array, sorting arrays, performing matrix multiplication, and illustrating the use of two-dimensional and three-dimensional arrays. Each section provides both theoretical explanations and practical Java code examples.

Uploaded by

nikhilaeede
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT –III ARRAYS

Topic: Arrays

1. Write a java program to find the greatest number present in an array of


whose size is 8. .[7M]Jan2023
2. Define an array? In what way an array variable differs from normal
variable? How can we declare and initialize them? Explain. [7M]Jan2023
3. Write a java program to sort the elements of an array in descending order.
[7M]Jan2023
4. Develop a Java program to perform the multiplication of two matrices
after verifying the compatibility conditions. .[7M]Jan2023
5. List the advantages of arrays over normal variables. Write a java program
to find the minimum and maximum value present in an array.
[7M]Jan2023
6. Illustrate usage of arrays two–dimensional and three - dimensional with
an example program. .[7M]July2023

Topic: Inheritance

7. How can we implement multiple inheritances in java. Explain.


.[7M]Jan2023
8. List the advantages of Inheritance. Write a program to demonstrate the
single level inheritance. .[7M]Jan2023
9. List out and explain the advantages of Inheritance. Discuss the types of
Inheritance supported by Java and explain the significance of ‘Super’
keyword. .[7M]Jan2023
10. What is inheritance? Explain different forms of inheritance with suitable
program segments and real-world example classes. .[7M]July2023
11. With the help of example program explain how to implement multiple
inheritances in java. .[7M]Jan2023

Topic: Interfaces

12. What is an interface? What is its role in java programming? Explain.


.[7M]Jan2023
13. Write short notes on Interfaces, Nested interfaces and functional
interfaces in Java. .[7M]Jan2023
14. How can we implement interfaces? Explain with example program.
.[7M]Jan2023

Topic: Method Overriding

15. Describe the method overriding with suitable example. .[7M]Jan2023

Topic: Abstract Classes, Super keyword

16. Write short notes on super keyword and abstract classes. [7M]Jan2023
17. Describe the importance of super keyword in java programming.
[7M]Jan2023

Topic: Dynamic Method Dispatch

18. Write a java program to demonstrate the concept of Dynamic method


dispatch and Trace the output to explain the same.[7M]Jan2023
19. Write a runtime polymorphism program in Java by using interface
reference variable. .[7M]July2023
20. What is meant by dynamic method dispatch? Explain with a
program.[7M]July2023
1. Write a java program to find the greatest number present in an array of whose size
is 8.
public class LargestElement_array {
public static void main(String[] args)
{

//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56,66,55,35};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
}

Output:

Largest element present in given array: 75

2. Define an array? In what way an array variable differs from normal


variable? How can we declare and initialize them? Explain.

Normally, an array is a collection of similar type of elements which has contiguous


memory location.

Java array is an object which contains elements of a similar data type.


Additionally, the elements of an array are stored in a contiguous memory location.
It is a data structure where we store similar elements. We can store only a fixed set
of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on.

Array holds multiple values, whereas an Normal variable hold a single value. it is
true when the elements of the array are treated as individual entities, and when the
variable is a simple scalar variable such as an int.

Creating, initializing, and accessing an Array

An array declaration has two components: the type and the name. type declares
the element type of the array. The element type determines the data type of each
element that comprises the array. Like an array of integers, we can also create an
array of other primitive data types like char, float, double, etc., or user-defined
data types (objects of a class). Thus, the element type for the array determines
what type of data the array will hold.

// both are valid declarations


int intArray[];
or int[] intArray;
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

Initializing an Array in Java

In Java, we can declare and initialize arrays at the same time.

 Initialization occurs when data is assigned to a variable.


 Declaration occurs when the variable is created.

So, when you first create a variable, you are declaring it but not necessarily
initializing it yet.

Here’s an example of how to declare and initialize values in Java:


//declare and initialize an array

int[] age = {25, 50, 23, 21};

Above, we declared an array using int[] age and initialized it by assigning the
values {25, 50, 23, 21}.

When an array is declared, only a reference of an array is created. To create or


give memory to the array, you create an array like this: The general form
of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number
of elements in the array, and var-name is the name of the array variable that is
linked to the array. To use new to allocate an array, you must specify the type
and number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array

Accessing and changing elements of an array

We access the elements of an array by referencing its index number. Remember,


the index begins with 0 and ends at the total array length, minus one. You can
access all elements of an array using a for loop. Loops are used in programming to
perform repetitive tasks that require conditions.

Example.

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo

3. Write a java program to sort the elements of an array in descending order.

In this program, we need to sort the given array in descending order such that
elements will be arranged from largest to smallest. This can be achieved through two
loops. The outer loop will select an element, and inner loop allows us to compare
selected element with rest of the elements.
Original Array
52871
Araay after Sorting
87521

Elements will be sorted in such a way that largest element will appear on extreme left
which in this case is 8. The smallest element will appear on extreme right which in
this case is 1.

public class SortDsc {


public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in descending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++)
{
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}

Output:

Elements of original array:


52871
Elements of array sorted in descending order:
87521

4. Develop a Java program to perform the multiplication of two matrices after


verifying the compatibility conditions.

import java.util.Scanner;
public class MatrixMultiplicationExample {

public static void main(String args[]) {


int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);

// Input dimensions of First Matrix: A


System.out.print("Enter number of rows in first matrix: ");
row1 = s.nextInt();

System.out.print("Enter number of columns in first matrix: ");


col1 = s.nextInt();

// Input dimensions of second matrix: B


System.out.print("Enter number of rows in second matrix: ");
row2 = s.nextInt();

System.out.print("Enter number of columns in second matrix: ");


col2 = s.nextInt();
// Requirement check for matrix multiplication
if (col1 != row2) {
System.out.println("Matrix multiplication is not possible");
return;
}

int a[][] = new int[row1][col1];


int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];

// Input the values of matrices


System.out.println("\nEnter values for matrix A : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) a[i][j] = s.nextInt();
}
System.out.println("\nEnter values for matrix B : ");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) b[i][j] = s.nextInt();
}

// Perform matrix multiplication


// Using for loop
System.out.println("\nMatrix multiplication is : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
// Initialize the element C(i,j) with zero
c[i][j] = 0;

// Dot product calculation


for (int k = 0; k < col1; k++) {
c[i][j] += a[i][k] * b[k][j];
}

System.out.print(c[i][j] + " ");


}
System.out.println();
}
}
}
5. List the advantages of arrays over normal variables. Write a java program to
find the minimum and maximum value present in an array.

Advantages of arrays :
 Efficient access to elements: Arrays provide direct and efficient access to any
element in the collection. Accessing an element in an array is an O(1)
operation, meaning that the time required to access an element is constant and
does not depend on the size of the array.
 Fast data retrieval: Arrays allow for fast data retrieval because the data is
stored in contiguous memory locations. This means that the data can be
accessed quickly and efficiently without the need for complex data structures
or algorithms.
 Memory efficiency: Arrays are a memory-efficient way of storing data.
Because the elements of an array are stored in contiguous memory locations,
the size of the array is known at compile time. This means that memory can be
allocated for the entire array in one block, reducing memory fragmentation.
 Versatility: Arrays can be used to store a wide range of data types, including
integers, floating-point numbers, characters, and even complex data structures
such as objects and pointers.
 Easy to implement: Arrays are easy to implement and understand, making
them an ideal choice for beginners learning computer programming.
 Compatibility with hardware: The array data structure is compatible with
most hardware architectures, making it a versatile tool for programming in a
wide range of environments.

Write a java program to find the minimum and maximum value present in an
array.

import java.util.*;
class ArrMinMax {
public static void main() {
Scanner inp = new Scanner(System.in);
System.out.print("\n Enter Size of Array: ");
int n = inp.nextInt();
int i, sum = 0;
int arr[] = new int[n]; //Creating N-size Array
for (i = 0; i < n; i++) { //Entering N numbers in array
System.out.print("\n Enter: ");
arr[i] = inp.nextInt();
}
int max_element = arr[0], min_element = arr[0]; //Initializing with first
element.

for (i = 0; i < n; i++) {


if (arr[i] > max_element) { //Checking Maximum element
max_element = arr[i];
}

if (arr[i] < min_element) { //Checking Minimum element


min_element = arr[i];
}
}

//Printing Result
System.out.println("\n Maximum Number: " + max_element);
System.out.println("\n Minimum Number: " + min_element);
}
6. Illustrate usage of arrays two–dimensional and three - dimensional with an
example program.

Usage of Arrays.

 Easy to use: Arrays are easy to use and require less coding than traditional
data structures. This makes arrays a great choice for rapid development.
 High performance: Arrays provide fast and efficient access to elements as
compared to other data structures such as linked lists, trees etc.
 Flexible size: The size of arrays can be changed easily at runtime, making
them a very flexible type of data structure.
 Memory efficient: Arrays are memory efficient as they can store multiple
values in the same location. This reduces the amount of RAM required to
store data and improves overall performance.
 Random Access: Arrays support random access, meaning elements can be
accessed directly using their index. This makes arrays an ideal choice for
applications requiring fast data access.
Two dimensional Array in java:-
A Two Dimensional Array in Java is a collection of 1D Array. It consists of rows
and columns and looks like a table. A 2D array is also known as Matrix.

Declaration Syntax of a Two Dimensional Array in Java

datatype variable_name[][] = new datatype[row_size][column_size];

Example:-
int a[][]=new int[3][3];

import java.util.Scanner;

public class Example


{
public static void main(String args[])
{
int a[][]=new int[3][3];
Scanner sc=new Scanner(System.in);
int r,c;
System.out.println("Enter 9 numbers");
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
a[r][c]=sc.nextInt();
}
}
System.out.println("\nOutput");
for(r=0; r<3; r++) // this loop is for row
{
for(c=0; c<3; c++) // this loop will print 3 numbers in each row
{
System.out.print(a[r][c]+" ");
}
System.out.println(); // break the line after printing the numbers in a row
}
}
}
Three Dimensional Array in java:-

An array with three indexes (subscripts) is called three dimensional array in


java.
In other words, a three-dimensional array is a collection of one or more two-
dimensional arrays, all of which share a common name.
It is distinguishable by the values of the first subscript of three dimensional array.
Thus, a three dimensional array is an array of two-dimensional arrays.
Uses of 3 dimensional array:-
Java three dimensional array is useful when we want to handle a group of elements
belonging to another group. For example, suppose a college has three departments:
Electronics, Computer Science, and Information Technology.
Syntax:-

int[ ][ ][ ] scores = new int[3][3][3];

Three Dimensional Array Example Program:-


public class ThreeDArray {
public static void main(String[] args)
{
int[ ][ ][ ] x;
x = new int[3][3][3];

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


{
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++)
x[i][j][k] = i + 1;
}
for(int i = 0; i < 3; i++)
{
System.out.println("Table-" +(i + 1));
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
System.out.print(x[i][j][k] +" ");
System.out.println();
}
System.out.println();
}
}
}

7. How can we implement multiple inheritances in java. Explain

Java and Multiple Inheritance


Multiple Inheritance is a feature of an object-oriented concept, where a class can
inherit properties of more than one parent class. The problem occurs when there
exist methods with the same signature in both the super classes and subclass. On
calling the method, the compiler cannot determine which class method to be
called and even on calling which class method gets the priority.

Multiple inheritance in java is the capability of creating a single class with multiple
super classes. Unlike some other popular object oriented programming languages
like C++, java doesn’t provide support for multiple inheritance in classes. Java
doesn’t support multiple inheritances in classes because it can lead to diamond
problem and rather than providing some complex way to solve it, there are better
ways through which we can achieve the same result as multiple inheritances.

Diamond Problem in Java To understand diamond problem easily, let’s


assume that multiple inheritances were supported in java. In that case, we could
have a class hierarchy like below image.

Multiple inheritance in Java programming is achieved or implemented using


interfaces. Java does not support multiple inheritance using classes.
In simple term, a class can inherit only one class and multiple interfaces in a java
programs. In java terminology, we can say that

“A class can extend only one class but it can implement multiple interfaces.”
For example, below inheritance using multiple classes is wrong as two classes
cannot be extended or inherited. Class C is inheriting class A and B.

8. List the advantages of Inheritance. Write a program to demonstrate the single


level inheritance.

Facilitating code reuse – Inheritance in Java programming allows for the reuse of
code, which can save time and effort when developing software.

Enhancing code modularity – By dividing code into parent and child classes,
inheritance can help to create more modular and organized code.

Improving code maintainability – Inheritance can make it easier to maintain code by


allowing developers to make changes in a single location that will be inherited by all
child classes.

Facilitating polymorphism – Inheritance allows for polymorphism, which enables


the creation of flexible and adaptable code that can be used in a variety of contexts.

Promoting code flexibility – Inheritance can make code more flexible by allowing
developers to create new classes that inherit the characteristics of existing classes,
while also adding their own unique features.

Write a program to demonstrate the single level inheritance.

class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
rect.display();
rect.area();
}
}

Output:-
Inside display
Inside area

9.10.11. List out and explain the advantages of Inheritance. Discuss the types
of Inheritance supported by Java and explain the significance of ‘Super’
keyword.

Inheritance is the most powerful feature of object-oriented programming. It


allows us to inherit the properties of one class into another class.

Inheritance is a mechanism of driving a new class from an existing class. The


existing (old) class is known as base class or super class or parent class. The new
class is known as a derived class or sub class or child class. It allows us to use the
properties and behavior of one class (parent) in another class (child).

A class whose properties are inherited is known as parent class and a class that
inherits the properties of the parent class is known as child class. Thus, it
establishes a relationship between parent and child class that is known as parent-
child or Is-a relationship.

Suppose, there are two classes named Father and Child and we want to inherit the
properties of the Father class in the Child class. We can achieve this by using
the extends keyword

Types of Inheritance

Java supports the following four types of inheritance:

o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Single Inheritance

o In single inheritance, a sub-class is derived from only one super class. It


inherits the properties and behavior of a single-parent class. Sometimes it is
also known as simple inheritance.

o
o In the above figure, Employee is a parent class and Executive is a child
class. The Executive class inherits all the properties of the Employee class.

Example:-

class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}

Output:-

Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0

Multi-level Inheritance

In multi-level inheritance, a class is derived from a class which is also derived


from another class is called multi-level inheritance. In simple words, we can say
that a class that has more than one parent class is called multi-level inheritance.
Note that the classes must be at different levels. Hence, there exists a single base
class and single derived class but multiple intermediate base classes.

In the above figure, the class Marks inherits the members or methods of the class
Students. The class Sports inherits the members of the class Marks. Therefore, the
Student class is the parent class of the class Marks and the class Marks is the
parent of the class Sports. Hence, the class Sports implicitly inherits the properties
of the Student along with the class Marks.

MultilevelInheritanceExample.java

//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
Output:-
registration number= 0987
marks= 78.0
score= 68.7

Hierarchical Inheritance

If a number of classes are derived from a single base class, it is called hierarchical
inheritance.

class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
Output:-
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.

Hybrid Inheritance

Hybrid means consist of more than one. Hybrid inheritance is the combination of
two or more types of inheritance.
In the above figure, GrandFather is a super class. The Father class inherits the
properties of the GrandFather class. Since Father and GrandFather represents
single inheritance. Further, the Father class is inherited by the Son and Daughter
class. Thus, the Father becomes the parent class for Son and Daughter. These
classes represent the hierarchical inheritance. Combinedly, it denotes the hybrid
inheritance.

Example:-

//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am daughter.
Multiple Inheritance (not supported)

Java does not support multiple inheritances due to ambiguity. For example,
consider the following Java program.

class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
Super key word:-
Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

Exmaple:-
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}

12.What is an interface? What is its role in java programming? Explain


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.
An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class. An interface in Java is a blueprint of a behaviour. A
Java interface contains static constants and abstract methods.

In other words, you can say that interfaces can have abstract methods and
variables.

 Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
 Interface do not have constructor.
 Represent behaviour as interface unless every sub-type of the class is
guarantee to have that behaviour.
 An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
Purpose of the interface
 Provides communication − One of the uses of the interface is to provide
communication. Through interface you can specify how you want the
methods and fields of a particular type.
 Multiple inheritance − Java doesn’t support multiple inheritance, using
interfaces you can achieve multiple inheritance

Example:-
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}
Programme:-

interface MyInterface1{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface1");
}
}
interface MyInterface2{
public static int num = 1000;
public default void display() {
System.out.println("display method of MyInterface2");
}
}
public class InterfaceExample implements MyInterface1, MyInterface2{
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
MyInterface1.super.display();
MyInterface2.super.display();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.show();
}
}
Output
display method of MyInterface1
display method of MyInterface2
13. Write short notes on Interfaces, Nested interfaces and functional
interfaces in Java

Interfaces:-

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.

Java Nested Interface:-

An interface, i.e., declared within another interface or class, is known as a nested


interface. The nested interfaces are used to group related interfaces so that they can
be easy to maintain. The nested interface must be referred to by the outer interface
or class. It can't be accessed directly.

Java Functional Interfaces:-


A functional interface is an interface that contains only one abstract method.
They can have only one functionality to exhibit. From Java 8 onwards, lambda
expressions can be used to represent the instance of a functional interface. A
functional interface can have any number of default methods.

An Interface that contains exactly one abstract method is known as functional


interface. It can have any number of default, static methods but can contain only
one abstract method. It can also declare methods of object class.

Functional Interface is also known as Single Abstract Method Interfaces or SAM


Interfaces. It is a new feature in Java, which helps to achieve functional
programming approach.

// Java program to demonstrate functional interface

class Test {
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable() {
@Override public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Output
New thread created

15. Describe the method overriding with suitable example

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method


that has been declared by one of its parent class, it is known as method overriding.

In java a child class can define methods with same signature as in parent class, if
we do so, we call this as method overriding. Method overriding is a technique in
java which allows java programmers to write methods in child class with same
signature as in parent class.

Programme:-

class Person {
void teach() {
System.out.println("I can teach");
}
}

class Teacher extends Person {


void teach() {
System.out.println("I teaches Computer Science");
}
public static void main(String [] args) {
Teacher teacher = new Teacher();
teacher.teach();
Person person = new Teacher();
person.teach();
Person person2 = new Person();
person2.teach();
}
}

16. 17. Write short notes on super keyword and abstract classes
Super Keyword in Java:-
The super keyword in Java is used in subclasses to access super class members
(attributes, constructors and methods).

The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

// Java code to show use of super


// keyword with variables

// Base class vehicle


class Vehicle {
int maxSpeed = 120;
}

// sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

Abstract Class:-

An abstract class in Java is one that is declared with the abstract keyword. It may
have both abstract and non-abstract methods(methods with bodies). An abstract is
a java modifier applicable for classes and methods in java but not for Variables.
In this article, we will learn the use of abstract class in java.
What is Abstract class in Java?
Java abstract class is a class that can not be initiated by itself, it needs to be sub
classed by another class to use its properties. An abstract class is declared using
the “abstract” keyword in its class definition.
Illustration of Abstract class
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
In Java, the following some important observations about abstract classes are as
follows:
1. An instance of an abstract class can not be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract method.
4. There can be a final method in abstract class but any abstract method in
class(abstract class) can not be declared as final or in simpler terms final
method can not be abstract itself as it will yield an error: “Illegal combination
of modifiers: abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes (Outer class)
as well as inner classes as abstract
7. If a class contains at least one abstract method then compulsory should
declare a class as abstract
8. If the Child class is unable to provide implementation to all abstract methods
of the Parent class then we should declare that Child class as abstract so that
the next level Child class should provide implementation to the remaining
abstract method.

Example of Abstract Class in Java:-

// Abstract class
abstract class Sunstar {
abstract void printInfo();
}

// Abstraction performed using extends


class Employee extends Sunstar {
void printInfo() {
String name = "avinash";
int age = 21;
float salary = 222.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);

// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}

18.Write a java program to demonstrate the concept of Dynamic method


dispatch and Trace the output to explain the same.

19. Write a runtime polymorphism program in Java by using interface


reference variable.

20.What is meant by dynamic method dispatch? Explain with a program.

Dynamic Method Dispatch or Runtime Polymorphism in Java

Runtime Polymorphism in Java is achieved by Method overriding in which a child


class overrides a method in its parent. An overridden method is essentially hidden
in the parent class, and is not invoked unless the child class uses the super keyword
within the overriding method. This method call resolution happens at runtime and
is termed as Dynamic method dispatch mechanism.

Method overriding is one of the ways in which Java supports Runtime


Polymorphism. Dynamic method dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather than compile time.
 When an overridden method is called through a superclass reference, Java
determines which version(superclass/subclasses) of that method is to be
executed based upon the type of the object being referred to at the time the
call occurs. Thus, this determination is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type
of the reference variable) that determines which version of an overridden
method will be executed
 A superclass reference variable can refer to a subclass object. This is also
known as upcasting. Java uses this fact to resolve calls to overridden methods
at run time.

class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {

Animal a = new Animal(); // Animal reference and object


Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run

In the above example, you can see that even though b is a type of Animal it runs
the move method in the Dog class. The reason for this is: In compile time, the
check is made on the reference type. However, in the runtime, JVM figures out the
object type and would run the method that belongs to that particular object.

Therefore, in the above example, the program will compile properly since Animal
class has the method move. Then, at the runtime, it runs the method specific for
that object.

You might also like