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

Inheritance-Interface

Uploaded by

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

Inheritance-Interface

Uploaded by

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

II.

Inheritance:
1. Introduction
• Inheritance is the backbone of object-oriented programming (OOP).
• It is the mechanism by which a class can acquire properties and methods of another
class.
• Using inheritance, an already tested and debugged class program can be reused for
some other application.
• Super class This is the existing class from which another class, that is, the subclass is
generally derived.
• In Java, several derived classes can have the same super class.
• Subclass A class that is derived from another class is called subclass.
• In Java, a subclass can have only one super class.

Benefits of Inheritance
• It allows the reuse of already developed and debugged class program without any
modification.
• It allows a number of subclasses to fulfil the needs of several subgroups.
• A large program may be divided into suitable classes and subclasses that may be
developed by separate teams of programmers.

Disadvantages of Inheritance
1. The tight coupling between super and subclasses increases and it becomes very difficult
to use them independently.
2. Program processing time increases as it takes more time for the control to jump
through various levels of overloaded classes.
3. When some new features are added to super and derived classes as a part of
maintenance, the changes affect both the classes.
4. When some methods are deleted in super class that is inherited by a subclass, the

33
WWW.JNTUKNOTES.COM/
methods of subclass will no longer override the super class method.
2. Process of Inheritance
• Inheritance means deriving some characteristics from something that is generic.
• In the context of Java, it implies deriving a new class from an existing old class, that is,
the super class.
• A super class describes general characteristics of a class of objects.
• A subset of these objects may have characteristics different from others.
• There are two ways of dealing with this problem.
• Either, make a separate class for the subset to include all the characteristics or, to have
another class that inherits the existing class, extend this class to include the special
characteristics.

34
WWW.JNTUKNOTES.COM/
3. Types of Inheritances
The following types of inheritances are supported by Java.
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance using interfaces

i. Single inheritance: It is the simple type of inheritance. In this, a class extends


another one class only.

Example: SingleInheritance.java
class DemoA
{
void displayA()
{
System.out.println("Super Class Method");
}
}
class DemoB extends DemoA
{
void displayB()
{
System.out.println("Sub Class Method");
}
}
class SingleInheritance
{
public static void main(String args[])
{
DemoA objA = new DemoA();
objA.displayA();

DemoB objB = new DemoB();


objB.displayB();
}
}
Output:
C:\>javac SingleInheritance.java
C:\>java SingleInheritance
Super Class Method
Sub Class Method

35
WWW.JNTUKNOTES.COM/
ii. Multilevel inheritance: In this type, a derived class inherits a parent

or super class; The derived class also acts as the parent class to other class.

Example: Multilevel.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}

class DemoB extends DemoA


{
void displayB()
{
System.out.println("Class-B Method");
}
}

class DemoC extends DemoB


{
void displayC()
{
System.out.println("Class-C Method");
}
}

class Multilevel
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();

36
WWW.JNTUKNOTES.COM/
//calling class-B method
DemoB objB = new DemoB();
objB.displayB();

//calling class-C method


DemoC objC = new DemoC();
objC.displayC();
}
}
Output:
C:\>javac Multilevel.java

C:\>java Multilevel
Class-A Method
Class-B Method
Class-C Method

iii. Hierarchical inheritance: In this type, one class is inherited by many sub classes.

Example: Hierarchical.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}

class DemoB extends DemoA


{
void displayB()
{
System.out.println("Class-B Method");

37
WWW.JNTUKNOTES.COM/
}
}

class DemoC extends DemoA


{
void displayC()
{
System.out.println("Class-C Method");
}
}

class Heirarchical
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();

//calling class-B method


DemoB objB = new DemoB();
objB.displayB();

//calling class-C method


DemoC objC = new DemoC();
objC.displayC();
}
}

Output:

C:\ >javac Hierarchical.java

C:\ >java Hierarchical


Class-A Method
Class-B Method
Class-C Method

38
WWW.JNTUKNOTES.COM/
iv. Multiple inheritance: In this, a class is extending more than one class.
• Java does not support multiple inheritance.
• This implies that a class cannot extend more than one class.
• Suppose there is a method in class A. This method is overridden in class B and class C
in their own way.
• Since class C extends both the classes A and B.
• So, if class C uses the same method, then there will be ambiguity as which method is
called.

Example: Multiple.java

interface X
{
int x=10;
}

interface Y
{
int y=20;
}

class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}
39
WWW.JNTUKNOTES.COM/
class DemoB extends DemoA implements X,Y
{
void displayB()
{
System.out.println("Class-B Method : x+y = " +
(x+y));
}
}

class Multiple
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.displayA();

//calling class-B method


DemoB objB = new DemoB();
objB.displayB();

}
}

Output:
C:\ >javac Multilevel.java

C:\ >java Multilevel


Class-A Method
Class-B Method
Class-C Method

40
WWW.JNTUKNOTES.COM/
4. Universal Super Class : “ Object ” Class
• Object class is a special class and it is at the top of the class hierarchy tree.
• It is the parent class or super class of all in Java.
• Hence, it is called Universal super class.
• Object is at the root of the tree and every other class can be directly or indirectly
derived from the Object class.

Example:ObjectEquals.java
class DemoA
{
void displayA()
{
System.out.println("Class-A Method");
}
}

class ObjectEquals
{
public static void main(String args[])
{
DemoA obj1 = new DemoA();
DemoA obj2 = new DemoA();
boolean test;

41
WWW.JNTUKNOTES.COM/
//Checking - if both object are equal
test = obj1.equals(obj2);
display(test);

// Object assignment
obj1=obj2;

//Checking - if both object are equal after assigning the


objects
test = obj1.equals(obj2);
display(test);
}

public static void display(boolean test)


{
if (test)
System.out.println("Both objects are same");
else
System.out.println("Both objects are different");
}
}

Output:

C:\>javac ObjectEquals.java

C:\>java ObjectEquals
Both objects are different
Both objects are same

42
WWW.JNTUKNOTES.COM/
5. Inhibiting Inheritance of Class Using Final
• A class declared as final cannot be inherited further.
• Class variables or instance variables are declared as constant to make local
variables.
• When a class is inherited by other classes, its methods can be overridden.
• In order to prevent the methods from being overridden, that method can be
declared as final.
Example:FinalClass.java
final class A
{
int a;
A(int x) {a=x;}
void display()
{
System.out.println("a = "+ a);
}
}

class B extends A
{
int b;
B(int x,int y)
{
super(x);
this.b=y;
}
void display()
{
System.out.println("b = "+ b);
}
}

class FinalClass
{
public static void main (String args[])
{
A objA= new A(10);
B objB= new B(100,200);

objA.display();
objB.display();
}
}
Output:
C:\>javac FinalClass.java
FinalClass.java:11: error: cannot inherit from final A
class B extends A
^
1 error
43
WWW.JNTUKNOTES.COM/
6. Access Control and Inheritance
• A derived class access to the members of a super class may be modified by
access specifiers.
• There are three access specifiers, that is, public, protected, and private.
• The code for specifying access is Access-specifier type member_identifier;

44
WWW.JNTUKNOTES.COM/
Example-1: DefaultAccess.java
class DemoA
{
int a;
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}

class DemoB extends DemoA


{
int b;
void displayB()
{
System.out.println("Class-B Method : a = " + a + " b = " + b );
}
}

class DefaultAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA();
objA.a=100; // accessing all classes in the same package
objA.displayA();

//calling class-B method


DemoB objB = new DemoB();
objB.a=200; // objA and objB are different objects. a is
assigned with 200
objB.b=300; // accessing all classes in the same package
objB.displayB();

}
}

Output:
C:\>javac DefaultAccess.java

C:\>java DefaultAccess
Class-A Method : a = 100
Class-B Method : a = 200 b = 300

45
WWW.JNTUKNOTES.COM/
Example -2: PrivateAccess.java
class DemoA
{
private int a;
DemoA(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}

class DemoB extends DemoA


{
int b;
DemoB(int p, int q)
{
super(p);
b=q;
}
void displayB()
{
displayA();
System.out.println("Class-B Method : b = " + b );
}
}

class PrivateAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(150);
//objA.a=100; // Error, Can't access private variable
objA.displayA();

//calling class-B method


DemoB objB = new DemoB(500,1000);
// objB.a=200; // objA and objB are different objects. Error,
Can't access private variable
//objB.b=300; // accessing all classes in the same package
objB.displayB();

}
}

46
WWW.JNTUKNOTES.COM/
Output:
C:\>javac PrivateAccess.java

C:\>java PrivateAccess
Class-A Method : a = 150
Class-A Method : a = 500
Class-B Method : b = 1000

Example: ProtectedAccess.java
class DemoA
{
protected int a;
DemoA(int t)
{
a = t;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}

class DemoB extends DemoA


{
int b;
DemoB(int p, int q)
{
super(p);
b=q;
}
void displayB()
{
System.out.println("Class-B Method : a= " + a + " b = " + b );
}
}

class DemoC extends DemoB


{
int c;
DemoC(int x, int y, int z)
{
super(x,y);
c=z;
}
void displayC()
{
System.out.println("Class-B Method : a = " + a + " b = " + b +
" c = " + c);
}

47
WWW.JNTUKNOTES.COM/
}

class ProtectedAccess
{
public static void main(String args[])
{
//calling class-A method
DemoA objA = new DemoA(100);
//objA.a=100; // Error, Can't access protected variable
objA.displayA();

//calling class-B method


DemoB objB = new DemoB(200,300);
objB.displayB();

//calling class-C method


DemoC objC = new DemoC(250,500,750);
objC.displayC();

}
}

Output:
C:\>javac ProtectedAccess.java

C:\>java ProtectedAccess
Class-A Method : a = 100
Class-B Method : a= 200 b = 300
Class-B Method : a = 250 b = 500 c = 750

48
WWW.JNTUKNOTES.COM/
7. Multilevel Inheritance
In this type, a derived class inherits a parent or super class;
• The derived class also acts as the parent class to other class.

See Example : Multilevel.java

49
WWW.JNTUKNOTES.COM/
8. Application of Keyword Super
The keyword super is used for two purposes:
First, to distinguish between the variables having the same name in super class and
subclass.
• When the member is called with an object of subclass, the subclass value will be
presented and super class value will get hidden.
• For getting super class value, the keyword super is used.
Second, it is used in defining the constructor of subclass.
• Instead of repeating the assignment of variables of super class, we simply qualify
the variable with super.
Example: SuperDemo.java
class A
{
int a;
A(int x)
{
a = x;
}
void displayA()
{
System.out.println("Class-A Method : a = " + a);
}
}
class B extends A
{
int b;
B(int p, int q)
{
super(p); // Calling Super class Construtor
b=q;
}
void displayB()
{
// Refering Super class with super keyword
System.out.println("Class-B Method : a = " + super.a + " b = " + b );
}
}
class SuperDemo
{
public static void main(String args[])
{
//Creating class B object by calling sub class constructor
B objB = new B(500,1000);

//calling class-B method


objB.displayB();

}
}
Output:
C:\>javac SuperDemo.java
C:\>java SuperDemo

50
WWW.JNTUKNOTES.COM/
Class-B Method : a = 500 b = 1000

51
WWW.JNTUKNOTES.COM/
9. Constructor Method and Inheritance
• For getting super class value, the keyword super is used.
• Second, it is used in defining the constructor of subclass.
• Instead of repeating the assignment of variables of super class, we simply qualify
the variable with super.
• Example: SuperDemo.java

10.Method Overriding
• It is one of the ways in which polymorphism can be implemented.
• When both super class and its subclass contain a method that has the same name and type
signature, the super class definition of the method is overridden by definitions in
subclass.
• It is different from the overloaded method in which only the name is same but parameter
list has to be different either in type or in number of parameters or order of parameters.
• In the case of overloaded methods, the parameter lists are matched to choose the
appropriate method that may be in super class or subclass.
• When two methods with the same name and type signature are defined in super (base)
class as well as in subclass (derived class), the subclass definition overrides the super
class definition when the method is called by object of subclass;
• It will execute the method defined in subclass and hide the definition of super class.

Binding
• It involves associating the method call to method body. There are two types of binding as
follows:
Static binding : When the binding is performed at compile time by the compiler, it is
known as static or early binding.
• For instance, binding for all static, private, and final methods is done at the compile time.
Dynamic binding : It is also called late binding. Here, the compiler is not able to resolve the
call (or binding) at compile time.
• Method overriding is one such example where dynamic binding is involved.
• The basic difference between static and dynamic binding is that static binding occurs at
compile time, whereas dynamic binding happens at run time.

Example: MethodOverriding.java
class A
{
void display()
{
System.out.println("Super Class Method");
}
}

class B extends A
52
WWW.JNTUKNOTES.COM/
{
void display()
{
System.out.println("Sub Class Method");
}
}

class MethodOverriding
{
public static void main(String args[])
{
//calling the class A method
A objA = new A();
objA.display();

//calling the class B method


objA = new B();
objA.display();
}
}
Output:

C:\>javac MethodOverriding.java

C:\>java MethodOverriding
Super Class Method
Sub Class Method

11.Dynamic Method Dispatch


• It is a mechanism by which runtime polymorphism is achieved for overridden
method in Java.
• It is implemented through super class reference. A super class reference can refer
to an object of its subclass.
• A base class pointer can refer to derived class object. There may be many
subclasses inherited from a super class.
• Each subclass has its own version or definition of the overridden method.
• The dynamic method dispatch chooses the right version of the method
corresponding to the object reference.
• In the method, first a reference variable of super class is created.
• The value of subclass object is assigned to the variable and the overridden
method is called by the super class reference.

Example: MethodOverriding.java

53
WWW.JNTUKNOTES.COM/
12.Abstract Classes
The abstract keyword is a non-access modifier, used for classes and methods:

• Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
Example: Abstract.java
abstract class A
{
int a;
void setValue(int x)
{
a=x;
}
abstract void display();
}

class B extends A
{
int b;
void setValues(int x, int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " b = " + b);
}
}

class C extends A
{
int c;
void setValues(int x, int y)
{
a=x;
c=y;
}
void display()
{
System.out.println("Class-B Method : a = " + a + " c = " + c);
}
}

54
WWW.JNTUKNOTES.COM/
class Abstract
{
public static void main(String args[])
{
//calling class-B method
System.out.println("Through objB");
B objB = new B();
objB.setValues(10,20);
objB.display();

//calling class-C method


System.out.println("Through objC");
C objC = new C();
objC.setValues(150,250);
objC.display();
}
}

13.Interfaces and Inheritance.


• Multiple inheritance of classes is not permitted in Java.
• To some extent, this restriction can be overcome through interfaces.
• A class may implement more than one interface besides having one super class.
• An interface can extend one or more interfaces, and a class can also implement more
than one interface.
• An interface is a collection of constants and abstract methods that are implemented by a
class.
• An interface cannot implement itself like a class;
• An interface just contains the method head, and there is no method body. The class that
implements the interface contains the full definition of the method.

Example: Multiple.java

55
WWW.JNTUKNOTES.COM/
III. Interfaces:
1. Introduction
• https://www.w3schools.com/java/java_interface.asp
An interface is a completely "abstract class" that is used to group related methods
with empty bodies
• https://www.javatpoint.com/interface-in-java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
• https://www.geeksforgeeks.org/interfaces-in-java/
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
• An interface also introduces a new reference type.
• An interface represents an encapsulation of constants, classes, interfaces, and one or
more abstract methods that are implemented by a class.
• An interface does not contain instance variables.
• An interface cannot implement itself; it has to be implemented by a class.
• The methods in an interface have no body.
• Only headers are declared with the parameter list that is followed by a semicolon.
• The class that implements the interface has to have full definitions of all the abstract
methods in the interface.
• An interface can be implemented by any number of classes with their own definitions
of the methods of the interface.
• Different classes can have different definitions of the same methods but the
parameter list must be identical to that in the interface.
• Thus, interfaces provide another way of dynamic polymorphic implementation of
methods.
• Any number of interfaces can be implemented by a class.
• This fulfils the need for multiple inheritance.
• The multiple inheritances of classes are not allowed in Java, and therefore, interfaces
provide a stopgap arrangement.

Similarities between Interface and Class


• Declaring an interface is similar to that of class; the keyword class is replaced by
keyword interface.
• Its accessibility can be controlled just like a class.
• An interface declared public is accessible to any class in any package, whereas the ones
without an access specifier is accessible to classes in the same package only.
• One can create variables as object references of interface that can use the interface.
• It can contain inner classes (nested classes) and inner interfaces.
• Since Java 8, an interface can have full definitions of methods with default or static
modifiers.

56
WWW.JNTUKNOTES.COM/
2. Declaration of Interface
• Declaration of an interface starts with the access modifier followed by keyword
interface.
• It is in then followed by its name or identifier that is followed by a block of
statements;
• These statements contain declarations of variables and abstract methods.
• The variables defined in interfaces are implicitly public, static, and final.
• They are initialized at the time of declaration. The methods declared in an
interface are public by default.

Members of Interface
• The members declared in the body of the interface.
• The members inherited from any super interface that it extends.
• The methods declared in the interface are implicitly public abstract member
methods.
• The field variables defined in interfaces are implicitly public, static, and final.
• However, the specification of these modifiers does not create a compile-type
error.
• The field variables declared in an interface must be initialized; otherwise,
compile-type error occurs.
• Since Java SE8, static and default methods with full definition can also be
members of interface.

57
WWW.JNTUKNOTES.COM/
3. Implementation of Interface
Declaration of class that implements an interface

If a class extends another class as well as implements interfaces, it is declared as

4. Multiple Interfaces
• Multiple interfaces can also be implemented in Java.
• For this, the class implements all the methods declared in all the interfaces.
• When the class is declared, names of all interfaces are listed after the keyword
implements and separated by comma.
• As for example, if class A implements interfaces C and D, it is defined as

Example: Multiple.java

Interface References:
• For interface references, variables can be declared as object references.
• In this case, the object reference would use interface as the type instead of
class.
• The appropriate method is called on the basis of actual instance of the
interface that is being referred to.

58
WWW.JNTUKNOTES.COM/
Example: InterfaceRef.java
interface X
{
int x = 10;
public void display();
}

interface Y
{
int y = 20;
public void add();
}
class A implements X,Y
{
public void display()
{
System.out.println("Class-B Method : x = "+ x + " y = " + y);
}
public void add()
{
System.out.println("Class-B Method : x+y = "+ (x+y));
}
}

class InterfaceRef
{
public static void main(String args[])
{
//Reference of X
X objX = new A();
objX.display();

//Reference of Y
Y objY = new A();
objY.add();
}
}
Output:
C:\ >javac InterfaceRef.java

C:\ >java InterfaceRef


Class-B Method : x = 10 y = 20
Class-B Method : x+y = 30

59
WWW.JNTUKNOTES.COM/
5. Nested Interfaces
• An interface may be declared as a member of a class or in another
• interface.
• In the capacity of a class member, it can have the attributes that are applicable to other
class members.
• In other cases, an interface can only be declared as public or with
default (no-access modifier) access.
• Syntax of nested interface in another interface is given as

60
WWW.JNTUKNOTES.COM/
Example: NestedInterface.java
interface OuterX
{
int x = 10;
public interface InnerY
{
int y = 20;
}
}

class A implements OuterX, OuterX.InnerY


{
void display()
{
System.out.println("Class-A Method : x = "+ x + " y
= " + y);
}
}

class NestedInterface
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}
}

Output:
C:\ >javac NestedInterface.java

C:\ >java NestedInterface


Class-A Method : x = 10 y = 20

61
WWW.JNTUKNOTES.COM/
6. Inheritance of Interfaces
Inheritance of Interfaces is similar to the Inheritance of classes. Interface can be
derived from another interface.

Syntax:

access_specifier interface NewInterface extends OldInterface


{
//Body of the interface
}

Example:

interface A{}
interface B{}
interface C extends A,B
{
//Body of the interface
}

Example Program: InterfaceInheritance.java

interface X
{
int x = 10;
}

interface Y extends X
{
int y = 20;
}

class A implements Y
{
void display()
{
System.out.println("Class-A Method : x = "+ x + " y = " + y);
}
}
class InterfaceInheritance
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}

62
WWW.JNTUKNOTES.COM/
}
Output:
C:\1. JAVA\UNIT-3.3>javac InterfaceInheritance.java

C:\1. JAVA\UNIT-3.3>java InterfaceInheritance


Class-A Method : x = 10 y = 20

7. Default Methods in Interfaces


• The enhancement in Java 8 allowing the interface to have full definition of
default methods and static methods that are implicitly inherited by the class
implementing the interface.
• Java allows only one super class, by using default methods in interface java
allows that interface behaves just like an abstract super-class.
• New functionality can be added to the interface, which is inherited by
classes implementing the interface.
• The inherited methods are also members of the class, and therefore, these
maybe called other methods of class.
• A default method cannot be declared final.
• A default method cannot be synchronized; however, blocks of statements in
the default method may be synchronized.
• The object class is inherited by all classes. Therefore, a default method
should not override any non- final method of object class.

63
WWW.JNTUKNOTES.COM/
Example : DefaultMethods.java

interface X
{
int x = 10;
default void display()
{
System.out.println("Method in Interface X the value x
= " + x);
}
}

class A implements X
{

class DefaultMethods
{
public static void main(String args[])
{
//calling class-A method
A objA = new A();
objA.display();
}
}

Output:
C:\>javac DefaultMethods.java

C:\>java DefaultMethods
Method in Interface X the value x = 10

64
WWW.JNTUKNOTES.COM/
8. Static Methods in Interface
• The Java version 8 allows full definition of static methods in interfaces.
• A static method is a class method.
• For calling a static method, one does not need an object of class.
• It can simply be called with class name as
class_name.method_name()

Example: StaticMethods.java

interface X
{
int x = 10;
static void display()
{
System.out.println("Method in Interface X the value x
= " + x);
}
}

class StaticMethods
{
public static void main(String args[])
{
//calling static method by specifying interface X
X.display();
}
}
Output:
C:\>javac StaticMethods.java

C:\>java StaticMethods
Method in Interface X the value x = 10

65
WWW.JNTUKNOTES.COM/
Java Lambda Expressions
• Lambda Expressions were added in Java 8.
• A lambda expression is a short block of code which takes in parameters and returns a
value.
• Lambda expressions are similar to methods, but they do not need a name and they can
be implemented right in the body of a method.
Syntax
The simplest lambda expression contains a single parameter and an expression:
Parameter -> expression

To use more than one parameter, wrap them in parentheses:

(Parameter1, Parameter2) -> { Code of Block }

Example1:
import java.util.ArrayList;

public class LambdaExpressions


{
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(9);
numbers.add(8);
numbers.add(1);
numbers.forEach((n) -> { System.out.println(n); });
}
}

C:\>javac LambdaExpressions.java

C:\>java LambdaExpressions
5
9
8
1

C:\1. JAVA\UNIT-3.3>

66
WWW.JNTUKNOTES.COM/
9. Functional Interfaces
• In Java SE8, a new package java.util.function on functional interfaces has been introduced
for writing Lambda functions.
• Functional interfaces are interfaces with one abstract method.
• They are also called SAM or single abstract method type.
• However, a functional interface can have more than one static and default methods.
• The programmer may include an annotation, to lessen the work of complier.
@FunctionalInterface
• By adding the above annotation, it can be helpful in detecting compile time errors.
• If the functional interface contains more than one abstract method, the compiler will throw
an error.

Example:Funcanal.java

import java.util.function.Function;
import java.util.function.BinaryOperator;

class Functional
{
public static void main(String args[])
{
//declaring logrithm and minimum as functional interfaces
Function <Double, Double> logrithm = Math::log;
BinaryOperator<Integer> minimum = Math::min;

//calling logrithm.apply() which is method reference to


the Function
System.out.println("Log of 10 to the base e = "+
logrithm.apply(10.0));

//calling minimum.apply() which is method reference to


the BinaryOperator
System.out.println("Minimum of 20 and 46 is "+
minimum.apply(20,46));
}
}

Output:
C:\ >javac Functional.java

C:\ >java Functional


Log of 10 to the base e = 2.302585092994046
Minimum of 20 and 46 is 20

67
WWW.JNTUKNOTES.COM/
Functional Consumer<T>
• The interface declaration is
@FunctionalInterface
public interface Consumer {void accept(T t);}
• It declares one abstract method void accept(T t).
• The method only consumes its argument. It does not give any return value.

Example: ConsumerDemo.java

import java.util.function.Consumer;

class ConsumerDemo
{
public static void main(String args[])
{
//declaring logrithm and minimum as functional interfaces
System.out.print("double value = ") ;
Consumer<Double> FunInt1 = (Double d) -> { display(d); };
FunInt1.accept(3.14);

System.out.print("\nString Array = ") ;


Consumer<String> FunInt2 = (String s) -> { display(s); };
String[] sray = {"CSE","ECE","CIVIL"};
for(String str: sray)
FunInt2.accept(str);

System.out.print("\nInteger Array = ") ;


Consumer<Integer> FunInt3 = (Integer n) -> { display(n); };
Integer[] iray = {1,2,3,4,5};
for(Integer num: iray)
FunInt3.accept(num);
}
public static<T> void display(T t)
{
System.out.print(t +" ");
}
}
Output:
C:\ >javac ConsumerDemo.java

C:\ >java ConsumerDemo


double value = 3.14
String Array = CSE ECE CIVIL
Integer Array = 1 2 3 4 5
68
WWW.JNTUKNOTES.COM/
10.Annotations.
• Annotation framework in Java language was first introduced in Java 5 through a
provisional interface Apt; It is a type of metadata that can be integrated with the source
code without affecting the running of the program.
Example: Annotational.java

class A
{
public void display()
{
System.out.println("In class A");
}
}

class B extends A
{
@Override public void display()
{
System.out.println("In class B");
}
}

class C extends A
{
@Override public void display()
{
System.out.println("In class C");
}
}
class Annotational
{
public static void main(String args[])
{
A objA = new A();
B objB = new B();
C objC = new C();

69
WWW.JNTUKNOTES.COM/
objA.display();
objB.display();
objC.display();
}
}

Output:
C:\1. JAVA\UNIT-3.3>javac Annotational.java

C:\1. JAVA\UNIT-3.3>java Annotational


In class A
In class B
In class C

If we change the method name in class C as displayC( ), Error will generate as

C:\1. JAVA\UNIT-3.3>javac Annotational.java


Annotational.java:19: error: method does not override or implement a
method from a supertype
@Override public void displayC()
^
1 error

You might also like