Java Interfaces in Amity School of Engineering & Technology

 
INTERFACE
 
Interface
 
Java does not support multiple inheritance.
In other words, classes in Java cannot have more than one
super class.
 
For example, a definition like
 
class 
One 
extends 
Two, Three
 
{         ……………………     }
 
is not permitted in Java.
 
However, Java provides an alternate approach known as
interfaces
 to support the concept of multiple inheritance.
 
2
 
Interface
 
An interface is a reference type in Java. It is
similar to class. It is a collection of abstract
methods.
A
n
 
I
n
t
e
r
f
a
c
e
 
i
n
 
J
a
v
a
 
p
r
o
g
r
a
m
m
i
n
g
 
l
a
n
g
u
a
g
e
 
i
s
d
e
f
i
n
e
d
 
a
s
 
a
n
 
a
b
s
t
r
a
c
t
 
t
y
p
e
 
u
s
e
d
 
t
o
 
s
p
e
c
i
f
y
 
t
h
e
b
e
h
a
v
i
o
r
 
o
f
 
a
 
c
l
a
s
s
.
 
A
n
 
i
n
t
e
r
f
a
c
e
 
i
n
 
J
a
v
a
 
i
s
 
a
b
l
u
e
p
r
i
n
t
 
o
f
 
a
 
c
l
a
s
s
.
 
A
 
J
a
v
a
 
i
n
t
e
r
f
a
c
e
 
c
o
n
t
a
i
n
s
s
t
a
t
i
c
 
c
o
n
s
t
a
n
t
s
 
a
n
d
 
a
b
s
t
r
a
c
t
 
m
e
t
h
o
d
s
.
 
3
 
Interface
 
An interface is basically a kind of class.
Like classes, interfaces contain methods and
variables but with a major difference.
The difference is that interfaces define only
abstract methods
 and 
final fields
.
This means that interfaces do not specify any
code to implement these methods and data
fields contain only constants.
Therefore, it is the responsibility of the class that
implements an interface to define the code for
implementation of these methods.
 
4
 
Cont..
 
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.
 
5
 
Syntax
 
interface {
// declare constant fields
// declare methods that abstract // by default.
}
To declare an interface, use the interface keyword. It
is used to provide total abstraction. That means all
the methods in an interface are declared with an
empty body and are public and all fields are public,
static, and final by default. A class that implements an
interface must implement all the methods declared in
the interface. To implement interface use implements
keyword.
 
6
 
Cont..
 
W
h
y
 
u
s
e
 
i
n
t
e
r
f
a
c
e
s
 
w
h
e
n
 
w
e
 
h
a
v
e
a
b
s
t
r
a
c
t
 
c
l
a
s
s
e
s
?
The reason is, abstract classes may contain
non-final variables, whereas variables in the
interface are final, public and static.
 
7
 
Class Vs Interface
 
8
 
Example
 
interface
 Itface
 
{    
static final
 
int
 i = 100 ;
  
static final
 
String
 name = 
new
          String
(“Gautam”) ;
  
void 
display( ) ;
 
}
Note that the code for the method is not included in
the interface and the method declaration simply ends
with a semicolon.
The class that implements this interface must define
the code for the method.
 
9
 
Extending Interfaces
 
Like classes, interfaces can also be extended.
That is, an interface can be sub interfaced from
other interfaces.
The new sub interface will inherit all the
members of the super interface in the manner
similar to sub classes.
This is achieved using the keyword 
extends
 as
shown below:
 
i
n
t
e
r
f
a
c
e
 
n
a
m
e
2
 
e
x
t
e
n
d
s
 
n
a
m
e
1
{
b
o
d
y
 
o
f
 
n
a
m
e
2
}
 
10
 
Example
 
Interface animal
{
       public void eat();
       public void travel();
}
 
Save As animal.java
 
11
 
Cont..
 
Public class mint implements animal {
    Public void eat() {
       System.out.println(“Mammal eats”);
     }
      Public void travel() {
       System.out.println(“Mammal travels”);
     }
      Public void nooflegs() {
       return 0;
     }
 
12
 
Cont..
 
public static void main(String args[]){
        mint obj=new mint();
        obj.eat();
        obj.travel();
    }
}
 
13
 
Advantages of Interfaces in Java
 
Without bothering about the implementation part, we
can achieve the security of the implementation.
In Java, multiple inheritance is not allowed, however,
you can use an interface to make use of it as you can
implement more than one interface.
 
14
 
Important Points
 
While interfaces are allowed to extend to other interfaces,
sub interfaces cannot define the methods declared in the
super interfaces.
After all, sub interfaces are still interfaces, not classes.
Instead, it is the responsibility of any class that implements
the derived interface to define all the methods.
Note that when an interface extends two or more interfaces,
they are separated by commas.
It is important to remember that an interface cannot extend
classes. This would violate the rule that an interface can
have only abstract methods and constants.
 
15
 
Implementing Interfaces
 
Interfaces are used as super classes whose properties are
inherited by classes.
 
It is therefore necessary to create a class that inherits the
given interface. This is done as follows:
 
 
class
 
class_name
 
implements
 
interface_name
 
{
  
body of class_name
 
}
 
16
 
Implementing Interfaces
 
Here the class 
class_name
 implements the interface
interface_name
.
 
A more general form of implementation may look like this:
 
 
class
 
class_name
 
extends
 
super_class
 
implements
interface-1, interface-2,…….interface-n
 
{
  
body of class_name
 
}
 
17
 
C
o
n
t
.
 
This shows that a class can extend another class while
implementing interfaces.
When a class implements more than one interface, they
are separated by comma.
N
o
w
,
 
c
o
n
s
i
d
e
r
 
t
h
e
 
f
o
l
l
o
w
i
n
g
 
p
r
o
g
r
a
m
.
 
I
n
 
t
h
i
s
 
p
r
o
g
r
a
m
,
 
a
n
 
i
n
t
e
r
f
a
c
e
 
A
r
e
a
 
i
s
 
c
r
e
a
t
e
d
.
 
T
h
i
s
 
i
n
t
e
r
f
a
c
e
i
s
 
i
m
p
l
e
m
e
n
t
e
d
 
f
o
r
 
t
w
o
 
d
i
f
f
e
r
e
n
t
 
c
l
a
s
s
e
s
,
 
R
e
c
t
a
n
g
l
e
 
a
n
d
C
i
r
c
l
e
.
 
I
n
 
t
h
e
 
m
a
i
n
 
m
e
t
h
o
d
,
 
t
h
e
 
i
n
s
t
a
n
c
e
s
 
o
f
 
b
o
t
h
 
t
h
e
c
l
a
s
s
e
s
 
a
r
e
 
c
r
e
a
t
e
d
.
 
A
f
t
e
r
 
t
h
i
s
,
 
t
h
e
 
o
b
j
e
c
t
 
o
f
 
t
h
e
 
i
n
t
e
r
f
a
c
e
A
r
e
a
 
i
s
 
c
r
e
a
t
e
d
 
a
n
d
 
t
h
e
 
r
e
f
e
r
e
n
c
e
 
t
o
 
t
h
e
 
R
e
c
t
a
n
g
l
e
 
o
b
j
e
c
t
r
 
i
s
 
a
s
s
i
g
n
e
d
 
t
o
 
t
h
i
s
 
o
b
j
e
c
t
.
 
W
h
e
n
 
t
h
e
 
c
o
m
p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i
c
 
d
o
u
b
l
e
 
c
o
m
p
u
t
e
(
d
o
u
b
l
e
 
x
,
 
d
o
u
b
l
e
 
y
)
 
 
{
 
 
 
 
r
e
t
u
r
n
(
p
i
*
x
*
x
)
;
 
 
}
}
 
Cont.
 
 
class 
Interface_Example
{
  
 
public static void
 main(String args[])
  
 
{
    
 
    Rectangle r = 
new 
Rectangle( );
    
 
    Circle c = 
new
 Circle( );
    
 
    Area a ;  
// Object of the Interface
    
 
    a = r ;
    
 
    System.out.println("\n  Area of Rectangle = " + a.compute(15.5, 12.3));
    
 
    a = c ;
    
 
    System.out.println("  Area of Circle = " + a.compute(12.5, 0.0));
    
 
}
}
 
O
u
t
p
u
t
:
 
Area of Rectangle = 190.65
 
Area of Circle = 490.625
 
Accessing Interface Variables
 
Interfaces can be used to declare a set of constants that
can be used in different classes.
 
T
h
i
s
 
i
s
 
s
i
m
i
l
a
r
 
t
o
 
c
r
e
a
t
i
n
g
 
h
e
a
d
e
r
 
f
i
l
e
s
 
i
n
 
C
+
+
 
t
o
 
c
o
n
t
a
i
n
 
a
l
a
r
g
e
 
n
u
m
b
e
r
 
o
f
 
c
o
n
s
t
a
n
t
s
.
 
Since such interfaces do not contain methods, there is no
need to worry about implementing any methods.
 
The constant values will be available to any class that
implements the interface.
 
The values can be used in any method, as part of any
variable declaration, or anywhere where one can use a
final value.
 
Cont.
 
For example, consider the following segment:
 
i
n
t
e
r
f
a
c
e
 
A
{
i
n
t
 
m
 
=
 
1
0
 
;
i
n
t
 
n
 
=
 
5
0
 
;
}
c
l
a
s
s
 
B
 
i
m
p
l
e
m
e
n
t
s
 
A
{
i
n
t
 
x
 
=
 
m
 
;
v
o
i
d
 
m
e
t
h
o
d
B
(
i
n
t
 
s
i
z
e
)
{
.
i
f
 
(
s
i
z
e
 
<
 
n
)
.
}
}
 
Hybrid Inheritance in Java
Student
Test
Sports
Results
 
c
l
a
s
s
 
i
n
t
e
r
f
a
c
e
 
c
l
a
s
s
 
c
l
a
s
s
 
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 
Marks obtained
 
Part1 = 27.5
 
Part2 = 24.5
 
Sports Wt = 6.0
 
Total Score = 58.0
 
Dynamic Binding, using an interface
 
 
interface 
Shape
 
{
  
float
 PI=3.14F;
  
void
 displayArea();
 
}
 
class
 Circle 
implements 
Shape
 
{
  
private
 
float
 radius ;
  
public 
Circle(
float
 r)
  
{
 
radius = r;
  
}
  
public
 
void 
displayArea()
  
{   System.out.print(“\n Area of the Circle is: “ + (PI *radius*radius)  ) ;    }
 
}
 
class
 Rectangle 
implements
 Shape
 
{
  
private
 
float 
length, breadth;
  
public
 Rectangle(
float
 l,
 float
 b)
  
{
 
Length =l; breadth = b;
 
}
  
public 
void 
displayArea()
  
{   System.out.print(“\n Area of rectangle = “ + (length*breadth) )  ;       }
 
}
 
class
 ShapeRun
{
 
public
 
static void
 main(String args[])
 
{
  
Shape s ;
  
Circle c = new Circle(5.5f);
  
s = c ;
  
s.displayArea();
  
Rectangle r = new Rectangle(5.5f 3.5f) ;
  
s = r ;
  
s.displayArea();
 
}
}
 
O
u
t
p
u
t
:
 
W
h
e
n
 
t
o
 
u
s
e
 
t
h
e
 
i
n
t
e
r
f
a
c
e
 
a
n
d
 
a
n
 
a
b
s
t
r
a
c
t
 
c
l
a
s
s
?
 
I
n
t
e
r
f
a
c
e
s
 
a
r
e
 
u
s
e
f
u
l
 
w
h
e
n
 
y
o
u
 
d
o
 
n
o
t
 
w
a
n
t
 
c
l
a
s
s
e
s
t
o
 
i
n
h
e
r
i
t
 
f
r
o
m
 
u
n
r
e
l
a
t
e
d
 
c
l
a
s
s
e
s
 
j
u
s
t
 
t
o
 
g
e
t
 
t
h
e
r
e
q
u
i
r
e
d
 
f
u
n
c
t
i
o
n
a
l
i
t
y
.
 
F
o
r
 
e
x
a
m
p
l
e
,
 
l
e
t
 
B
i
r
d
 
b
e
 
a
 
c
l
a
s
s
 
w
i
t
h
 
a
 
m
e
t
h
o
d
f
l
y
(
)
.
 
I
t
 
w
i
l
l
 
b
e
 
r
i
d
i
c
u
l
o
u
s
 
f
o
r
 
a
n
 
A
e
r
o
p
l
a
n
e
 
t
o
 
i
n
h
e
r
i
t
f
r
o
m
 
B
i
r
d
 
c
l
a
s
s
 
j
u
s
t
 
b
e
c
a
u
s
e
 
i
t
 
h
a
s
 
t
h
e
 
f
l
y
(
)
m
e
t
h
o
d
.
 
R
a
t
h
e
r
 
t
h
e
 
f
l
y
(
)
 
m
e
t
h
o
d
 
s
h
o
u
l
d
 
b
e
 
d
e
f
i
n
e
d
 
a
s
 
a
n
i
n
t
e
r
f
a
c
e
 
a
n
d
 
b
o
t
h
 
B
i
r
d
 
a
n
d
 
A
e
r
o
p
l
a
n
e
 
s
h
o
u
l
d
i
m
p
l
e
m
e
n
t
 
t
h
a
t
 
i
n
t
e
r
f
a
c
e
.
 
W
h
e
n
 
t
o
 
u
s
e
 
t
h
e
 
i
n
t
e
r
f
a
c
e
 
a
n
d
 
a
n
 
a
b
s
t
r
a
c
t
 
c
l
a
s
s
?
(
A
n
 
e
x
a
m
p
l
e
)
 
Consider a real estate builder is constructing an
apartment with many flats. All the rooms in the
flats have the same design, except the bedroom.
The bedroom design is left for the people who
would own the flats i.e. the bedrooms can be of
different designs for different flats.
 
The solution to above can be achieved through an abstract
class like below:
 
public
 
abstract 
class
 Flat
{
  
//some properties / variables
 
public
 void
 livingRoom()
  
{
 
   
//some code
 
}
  
public
 void
 kitchen()
  
{
 
   
//some code
 
}
  
public 
abstract 
void
 bedRoom( );
}
 
public class
 Flat101 
extends
 Flat
{
 
public 
void
 bedRoom()
 
{
  
System.out.println("This flat has a customized bedroom");
 
}
}
 
Alternatively I can use an interface instead of an abstract class
to achieve the same purpose like follows:
 
class
 Flat
{
 
  
public
 
void 
livingRoom()
  
{  
 
System.out.println("This flat has a living room");      }
  
public
 
void 
kitchen()
  
{         
 
System.out.println("This flat has a kitchen");     }
}
interface
 BedRoomInterface
{
 
public
 
abstract void
 bedRoom();
}
public class
 Flat101 
extends 
Flat 
implements 
BedRoomInterface
{
  
public
 
void 
bedRoom()
  
{
   
System.out.println("This flat has a customized bedroom");
 
  
}
}
 
Now the question is:
 
For this setup why should I choose to use
an interface (or) why should I choose to use an abstract class?
 
A
n
 
i
n
t
e
r
f
a
c
e
 
w
o
u
l
d
 
b
e
 
b
e
s
t
 
c
h
o
i
c
e
 
f
o
r
 
a
b
o
v
e
 
c
a
s
e
.
 
B
e
c
a
u
s
e
y
o
u
 
g
o
t
 
t
h
e
 
m
e
t
h
o
d
 
w
h
i
c
h
 
g
o
t
 
v
a
r
i
o
u
s
 
i
m
p
l
e
m
e
n
t
a
t
i
o
n
s
.
 
S
o
i
t
'
s
 
t
h
e
 
k
e
y
 
c
o
n
c
e
p
t
 
i
f
 
y
o
u
r
 
m
e
t
h
o
d
s
 
g
o
t
 
v
a
r
i
o
u
s
i
m
p
l
e
m
e
n
t
a
t
i
o
n
s
 
y
o
u
 
s
h
o
u
l
d
 
a
l
w
a
y
s
 
g
o
 
f
o
r
 
i
n
t
e
r
f
a
c
e
.
 
T
h
i
s
 
i
s
 
b
e
c
a
u
s
e
 
w
h
e
n
 
y
o
u
 
d
e
f
i
n
e
 
a
n
 
o
b
j
e
c
t
 
o
f
 
t
h
e
 
c
l
a
s
s
 
F
l
a
t
1
0
1
 
y
o
u
w
i
l
l
 
h
a
v
e
 
a
c
c
e
s
s
 
t
o
 
a
l
l
 
t
h
e
 
m
e
t
h
o
d
 
a
n
d
 
c
a
n
 
a
n
y
 
t
i
m
e
 
t
a
m
p
e
r
 
t
h
e
i
m
p
l
e
m
e
n
t
a
t
i
o
n
.
 
On the other hand if you get the interface object, you can only
invoke the method but not modify. Security can be achieved through
interfaces
 
Interface Nesting
 
public interface outerinter{
     void display();
  interface Inner {
     void Innermethod();
    }
}
 
35
 
class fibo implements outerinter.Inner {
 
    public void Innermethod()
    {
         int n=10,t1=0,t2=1;
        System.out.println("First "+n+" terms");
        for(int i=1;i<=10; i++)
         {
               System.out.print(t1 + "+");
              int sum=t1+t2;
              t1=t2;
              t2=sum;
          }
 
36
 
System.out.println("Printing from nested interface method");
     }
     public static void main(String args[])
      {
           outerinter.Inner obj= new fibo();
           obj.Innermethod();
      }
 
37
 
New Features Added in Interfaces
in JDK 9
 
1.
Static methods
2.
Private methods
3.
Private Static methods
 
38
 
Static Method in Interface
 
Static Methods
 in 
Interface 
are those methods, which are
defined in the interface with the keyword static. Unlike
other methods in Interface, these static methods contain the
complete definition of the function and since the definition
is complete and the method is static, therefore these
methods cannot be overridden or changed in the
implementation class.
The static method in an interface can be defined in the
interface but cannot be overridden in Implementation
Classes. To use a static method, Interface name should be
instantiated with it, as it is a part of the Interface only.
 
39
 
Example
 
interface NewInterface {
     // static method
    static void hello()
    {
        System.out.println("Hello, New Static Method Here");
    }
     // Public and abstract method of Interface
    void overrideMethod(String str);
}
 
40
 
public class InterfaceDemo implements NewInterface {
     public static void main(String[] args)    {
        InterfaceDemo interfaceDemo = new InterfaceDemo();
         // Calling the static method of interface
        NewInterface.hello();
         // Calling the abstract method of interface
        interfaceDemo.overrideMethod("Hello, Override Methodhere");
    }     // Implementing interface method
     @Override
    public void overrideMethod(String str)
    {
        System.out.println(str);
    }
}
 
41
 
Scope of Static method.
 
T
he scope of the static method definition is within the
interface only. If same name method is implemented in
the implementation class then that method becomes a
static member of that respective class.
 
42
 
Example
 
43
interface
 
PrintDemo {
    
// Static Method
    
static
 
void
 
hello()
    
{
        
System.out.println(
"Called from Interface
PrintDemo"
);
    
}
}
 
Example
 
44
 
public
 
class
 
InterfaceDemo 
implements
 
PrintDemo {
    
public
 
static
 
void
 
main(String[] args)
    
{
        
// Call Interface method as Interface
        
// name is preceding with method
        
PrintDemo.hello();
        
// Call Class static method
        
hello();
    
}
    
// Class Static method is defined
    
static
 
void
 
hello()
    
{
        
System.out.println(
"Called from Class"
);
    
}
}
 
Private Method
 
interfaces are able to use private methods to hide details
on implementation from classes that implement the
interface. As a result, one of the main benefits of having
these in interfaces is encapsulation.
Another benefit is (as with private methods in general)
that there is less duplication and more re-usable code
added to interfaces for methods with similar
functionality.
 
45
 
Example
 
public
 
interface
 
Foo
 {
     
default
 
void
 
bar
() {
                  
System.out.print(
"Hello"
);
                  
baz();
            
}
         
private
 
void
 
baz
() {
                
System.out.println(
" world!"
);
         }
 }
 
46
 
Example
 
public
 
interface
 
Foo
 {
     
static
 
void
 
buzz
() {
            
 System.out.print(
"Hello"
);
             
 staticBaz();
        
 }
         
 
private
 
static
 
void
 
staticBaz
() {
                      
System.out.println(
" static world!"
);
         
}
 }
 
47
 
Cont.
 
public
 
class
 
CustomFoo
 
implements
 
Foo
 {
                   
public
 
static
 
void
 
main
(String... args) {
                          
Foo
 
customFoo
 = 
new
 
CustomFoo
();
                          
customFoo.bar();
                          
Foo.buzz();
                     
 }
 }
 
48
Slide Note
Embed
Share

Java interfaces are a key concept in object-oriented programming that allows for achieving multiple inheritance. The article discusses how Java interfaces work, their role in defining class behavior, and the differences between interfaces and classes. It also explains the syntax for declaring interfaces and the importance of using interfaces over abstract classes in Java programming.

  • Java Interfaces
  • Object-Oriented Programming
  • Amity School
  • Engineering & Technology
  • Java Syntax

Uploaded on Jul 09, 2024 | 4 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. Amity School of Engineering & Technology INTERFACE

  2. Amity School of Engineering & Technology Interface Java does not support multiple inheritance. In other words, classes in Java cannot have more than one super class. For example, a definition like class One extends Two, Three { is not permitted in Java. } However, Java provides an alternate approach known as interfaces to support the concept of multiple inheritance. 2

  3. Amity School of Engineering & Technology Interface An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. 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 class. A Java interface contains static constants and abstract methods. 3

  4. Amity School of Engineering & Technology Interface An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Therefore, it is the responsibility of the class that implements an interface to define the code for implementation of these methods. 4

  5. Amity School of Engineering & Technology Cont.. 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. 5

  6. Amity School of Engineering & Technology Syntax interface { // declare constant fields // declare methods that abstract // by default. } To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement interface use implements keyword. 6

  7. Amity School of Engineering & Technology Cont.. Why use interfaces when we have abstract classes? The reason is, abstract classes may contain non-final variables, whereas variables in the interface are final, public and static. 7

  8. Amity School of Engineering & Technology Class Vs Interface S. N. Class Interface In an interface, you can t instantiate variables and create an object. In class, you can instantiate variables and create an object. 1. The interface cannot contain concrete(with implementation) methods Class can contain concrete(with implementation) methods 2. The access specifiers used with classes are private, protected, and public. In Interface only one specifier is used- Public. 3. An interface does not contain any constructors. All the methods in an interface are abstract. Contain constructor No abstract method 4 8

  9. Amity School of Engineering & Technology Example interface Itface { static final int i = 100 ; static final String name = new String( Gautam ) ; void display( ) ; } Note that the code for the method is not included in the interface and the method declaration simply ends with a semicolon. The class that implements this interface must define the code for the method. 9

  10. Amity School of Engineering & Technology Extending Interfaces Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other interfaces. The new sub interface will inherit all the members of the super interface in the manner similar to sub classes. This is achieved using the keyword extends as shown below: interface name2 extends name1 { body of name2 } 10

  11. Amity School of Engineering & Technology Example Interface animal { public void eat(); public void travel(); } Save As animal.java 11

  12. Amity School of Engineering & Technology Cont.. Public class mint implements animal { Public void eat() { System.out.println( Mammal eats ); } Public void travel() { System.out.println( Mammal travels ); } Public void nooflegs() { return 0; } 12

  13. Amity School of Engineering & Technology Cont.. public static void main(String args[]){ mint obj=new mint(); obj.eat(); obj.travel(); } } 13

  14. Amity School of Engineering & Technology Advantages of Interfaces in Java Without bothering about the implementation part, we can achieve the security of the implementation. In Java, multiple inheritance is not allowed, however, you can use an interface to make use of it as you can implement more than one interface. 14

  15. Amity School of Engineering & Technology Important Points While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the methods declared in the super interfaces. After all, sub interfaces are still interfaces, not classes. Instead, it is the responsibility of any class that implements the derived interface to define all the methods. Note that when an interface extends two or more interfaces, they are separated by commas. It is important to remember that an interface cannot extend classes. This would violate the rule that an interface can have only abstract methods and constants. 15

  16. Amity School of Engineering & Technology Implementing Interfaces Interfaces are used as super classes whose properties are inherited by classes. It is therefore necessary to create a class that inherits the given interface. This is done as follows: classclass_nameimplementsinterface_name { body of class_name } 16

  17. Amity School of Engineering & Technology Implementing Interfaces Here the class class_name implements the interface interface_name. A more general form of implementation may look like this: classclass_nameextendssuper_classimplements interface-1, interface-2, .interface-n { body of class_name } 17

  18. Amity School of Engineering & Technology Cont. This shows that a class can extend another class while implementing interfaces. When a class implements more than one interface, they are separated by comma. Now, consider the following program. In this program, an interface Area is created. This interface is implemented for two different classes, Rectangle and Circle. In the main method, the instances of both the classes are created. After this, the object of the interface Area is created and the reference to the Rectangle object r is assigned to this object. When the compute method of a is called, the compute method of Rectangle is invoked. The same thing is repeated for the Circle object.

  19. Amity School of Engineering & Technology Program // This program illustrates the use of the interface, in multiple inheritance interface Area // Interface Definition { final static double pi = 3.14 ; double compute(double x, double y); } class Rectangle implements Area // Implementation of the interface { public double compute(double x, double y) { return (x*y); } } class Circle implements Area // Implementation of the interface { public double compute(double x, double y) { return(pi*x*x); } }

  20. Amity School of Engineering & Technology Cont. class Interface_Example { public static void main(String args[]) { Rectangle r = new Rectangle( ); Circle c = new Circle( ); Area a ; // Object of the Interface a = r ; System.out.println("\n Area of Rectangle = " + a.compute(15.5, 12.3)); a = c ; System.out.println(" Area of Circle = " + a.compute(12.5, 0.0)); } } Output: Area of Rectangle = 190.65 Area of Circle = 490.625

  21. Amity School of Engineering & Technology Accessing Interface Variables Interfaces can be used to declare a set of constants that can be used in different classes. This is similar to creating header files in C++ to contain a large number of constants. Since such interfaces do not contain methods, there is no need to worry about implementing any methods. The constant values will be available to any class that implements the interface. The values can be used in any method, as part of any variable declaration, or anywhere where one can use a final value.

  22. Amity School of Engineering & Technology Cont. For example, consider the following segment: interface A { int m = 10 ; int n = 50 ; } class B implements A { int x = m ; void methodB(int size) { . if (size < n) . } }

  23. Amity School of Engineering & Technology Hybrid Inheritance in Java Student class extends interface Sports class Test extends implements class Results

  24. Amity School of Engineering & Technology Example class Student // Super class { int roll_no ; void getNumber(int n) { void putNumber( ) { } // End of the super class roll_no = n ; } System.out.println("\n Roll no: = " + roll_no); } class Test extends Student // Sub class { float part1, part2 ; void getMarks(float m1, float m2) { part1 = m1 ; part2 = m2 ; void putMarks( ) { System.out.println(" Marks obtained" ); System.out.println(" Part1 = " + part1); System.out.println(" Part2 = " + part2); } } }

  25. Amity School of Engineering & Technology interface Sports { } class Results extends Test implements Sports { float total ; public void putWt( ) { System.out.println(" Sports Wt = " + sportWt); } void display( ) { total = part1 + part2 + sportWt ; putNumber( ); putMarks( ); putWt( ); System.out.println(" Total score = " + total); } } float sportWt = 6.0f ; void putWt( );

  26. Amity School of Engineering & Technology class Hybrid { } public static void main(String args[ ]) { Results student1 = new Results( ); student1.getNumber(1234); student1.getMarks(27.5f, 24.5f); student1.display( ); } Output: Roll no: = 1234 Marks obtained Part1 = 27.5 Part2 = 24.5 Sports Wt = 6.0 Total Score = 58.0

  27. Amity School of Engineering & Technology Dynamic Binding, using an interface interface Shape { float PI=3.14F; void displayArea(); } class Circle implements Shape { private float radius ; public Circle(float r) { radius = r; public void displayArea() { System.out.print( \n Area of the Circle is: + (PI *radius*radius) ) ; } } class Rectangle implements Shape { private float length, breadth; public Rectangle(float l, float b) { Length =l; breadth = b; public void displayArea() { System.out.print( \n Area of rectangle = + (length*breadth) ) ; } } } }

  28. Amity School of Engineering & Technology class ShapeRun { public static void main(String args[]) { Shape s ; Circle c = new Circle(5.5f); s = c ; s.displayArea(); Rectangle r = new Rectangle(5.5f 3.5f) ; s = r ; s.displayArea(); } } Output:

  29. Amity School of Engineering & Technology Abstract Class Interface Abstract classes are used only when there is a is-a type of relationship between the classes. You cannot extend more than one abstract class. Abstract class can implemented some methods also. With abstract classes, you are grabbing away each class s individuality. An abstract class can have instance methods that implement behavior. Interfaces can be implemented by classes that are not related to one another. You can implement more than one interface. Interfaces can not implement methods. With extending each class s functionality. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. Interfaces, you are merely a default An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

  30. Amity School of Engineering & Technology When to use the interface and an abstract class? Interfacesare useful when you do not want classes to inherit from unrelated classes just to get the required functionality. For example, let Bird be a class with a method fly(). It will be ridiculous for an Aeroplane to inherit from Bird class just because it has the fly() method. Rather the fly() method should be defined as an interface and both Bird and Aeroplane should implement that interface.

  31. Amity School of Engineering & Technology When to use the interface and an abstract class? (An example) Consider a real estate builder is constructing an apartment with many flats. All the rooms in the flats have the same design, except the bedroom. The bedroom design is left for the people who would own the flats i.e. the bedrooms can be of different designs for different flats.

  32. Amity School of Engineering & Technology The solution to above can be achieved through an abstract class like below: public abstract class Flat { //some properties / variables public void livingRoom() { //some code public void kitchen() { //some code public abstract void bedRoom( ); } } } public class Flat101 extends Flat { public void bedRoom() { System.out.println("This flat has a customized bedroom"); } }

  33. Amity School of Engineering & Technology Alternatively I can use an interface instead of an abstract class to achieve the same purpose like follows: class Flat { public void livingRoom() { System.out.println("This flat has a living room"); } public void kitchen() { System.out.println("This flat has a kitchen"); } } interface BedRoomInterface { public abstract void bedRoom(); } public class Flat101 extends Flat implements BedRoomInterface { public void bedRoom() { System.out.println("This flat has a customized bedroom"); } }

  34. Amity School of Engineering & Technology Now the question is:For this setup why should I choose to use an interface (or) why should I choose to use an abstract class? An interface would be best choice for above case. Because you got the method which got various implementations. So it's the key concept if your methods got various implementations you should always go for interface. This is because when you define an object of the class Flat101 you will have access to all the method and can any time tamper the implementation. On the other hand if you get the interface object, you can only invoke the method but not modify. Security can be achieved through interfaces

  35. Amity School of Engineering & Technology Interface Nesting public interface outerinter{ void display(); interface Inner { void Innermethod(); } } 35

  36. Amity School of Engineering & Technology class fibo implements outerinter.Inner { public void Innermethod() { int n=10,t1=0,t2=1; System.out.println("First "+n+" terms"); for(int i=1;i<=10; i++) { System.out.print(t1 + "+"); int sum=t1+t2; t1=t2; t2=sum; } 36

  37. Amity School of Engineering & Technology System.out.println("Printing from nested interface method"); } public static void main(String args[]) { outerinter.Inner obj= new fibo(); obj.Innermethod(); } 37

  38. Amity School of Engineering & Technology New Features Added in Interfaces in JDK 9 1.Static methods 2.Private methods 3.Private Static methods 38

  39. Amity School of Engineering & Technology Static Method in Interface Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementation class. The static method in an interface can be defined in the interface but cannot be overridden in Implementation Classes. To use a static method, Interface name should be instantiated with it, as it is a part of the Interface only. 39

  40. Amity School of Engineering & Technology Example interface NewInterface { // static method static void hello() { System.out.println("Hello, New Static Method Here"); } // Public and abstract method of Interface void overrideMethod(String str); } 40

  41. Amity School of Engineering & Technology public class InterfaceDemo implements NewInterface { public static void main(String[] args) { InterfaceDemo interfaceDemo = new InterfaceDemo(); // Calling the static method of interface NewInterface.hello(); // Calling the abstract method of interface interfaceDemo.overrideMethod("Hello, Override Methodhere"); } // Implementing interface method @Override public void overrideMethod(String str) { System.out.println(str); } }41

  42. Amity School of Engineering & Technology Scope of Static method. The scope of the static method definition is within the interface only. If same name method is implemented in the implementation class then that method becomes a static member of that respective class. 42

  43. Amity School of Engineering & Technology Example interface PrintDemo { // Static Method staticvoid hello() { System.out.println("Called from Interface PrintDemo"); } } 43

  44. publicclass InterfaceDemo implements PrintDemo { Amity School of Engineering & Technology Example publicstaticvoid main(String[] args) { // Call Interface method as Interface // name is preceding with method PrintDemo.hello(); // Call Class static method hello(); } // Class Static method is defined staticvoid hello() { System.out.println("Called from Class"); } 44 }

  45. Amity School of Engineering & Technology Private Method interfaces are able to use private methods to hide details on implementation from classes that implement the interface. As a result, one of the main benefits of having these in interfaces is encapsulation. Another benefit is (as with private methods in general) that there is less duplication and more re-usable code added to interfaces for methods with similar functionality. 45

  46. Amity School of Engineering & Technology Example publicinterfaceFoo { defaultvoidbar() { System.out.print("Hello"); baz(); } privatevoidbaz() { System.out.println(" world!"); } } 46

  47. Amity School of Engineering & Technology Example publicinterfaceFoo { staticvoidbuzz() { System.out.print("Hello"); staticBaz(); } privatestaticvoidstaticBaz() { System.out.println(" static world!"); } } 47

  48. Amity School of Engineering & Technology Cont. publicclassCustomFooimplementsFoo { publicstaticvoidmain(String... args) { Foo customFoo = newCustomFoo(); customFoo.bar(); Foo.buzz(); } } 48

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#