Sie sind auf Seite 1von 35

Programming in Java

Interfaces

By
Arvind Kumar
Asst. Professor, LPU
Interfaces
Interfaces
• An interface is a collection of abstract methods.

• An interface is a group of related methods with empty bodies.

• An interface is not a class.


• Writing an interface is similar to writing a class, but they are two
different concepts.
• A class describes the attributes and behaviors of an object whereas an
interface contains behaviors that a class implements.

• A class implements an interface, thereby inheriting the abstract methods


of the interface.

• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
Properties of Interfaces
• The interface keyword is used to declare an interface.

• Interfaces have the following properties:

– An interface is implicitly abstract. We do not need to use


the abstract keyword when declaring an interface.

– Each method in an interface is also implicitly abstract, so


the abstract keyword is not needed.

– Methods in an interface are implicitly public.


Interface Vs Class
An interface is similar to a class in the following ways:

• An interface can contain any number of methods.

• An interface is written in a file with a .java extension, with


the name of the interface matching the name of the file.

• The byte-code of an interface appears in a .class file.

• Interfaces appear in packages, and their corresponding byte-


code file must be in a directory structure that matches the
package name.
Interface Vs Class
An interface is different from a class in several ways,
including:

• We cannot instantiate an interface.

• An interface does not contain any constructors.

• All of the methods in an interface are abstract.

• An interface is not extended by a class; it is implemented by a


class.

• An interface can extend multiple interfaces.


Implementing Interfaces
• When a class implements an interface, then it has to
perform the specific behaviors of the interface.

• If a class does not perform all the behaviors of the


interface, the class must declare itself as abstract.

• A class uses the implements keyword to implement an


interface.

• The implements keyword appears in the class declaration


following the extends portion of the declaration.
Example

interface Animal
{
public void eat();
public void travel();
}
Example
public class Mammal implements Animal
{
public void eat()
{
System.out.println("Mammal eats");
}
public void travel()
{
System.out.println("Mammal travels");
}
public int noOfLegs()
{ return 0; }
public static void main(String args[])
{
Animal m = new Mammal();
m.eat();
m.travel();
}
}
Abstract Class Vs Interfaces
Abstract Class Interface

May contain non-abstract methods Contains only method declaration and


and non-static non final data members static final data members

Multiple Inheritance is not supported Multiple Inheritance through


through classes Interfaces is supported

Inheritance using ‘extends’ keyword Inheritance using ‘implements’


keyword
Why Interfaces?
Problem?
• Define a class named ‘Invoker’ that contains a static
method ‘invoke()’.

• ‘invoke ()’ receives an object of a class that contains


‘show()’.

• From the invoke() we have to invoke show() on the


argument object.
class Invoker
{
public static void invoke(___ x)
{
x.show();
}
}

Problem1: Type of argument object is not known…

Problem2: There is no guarantee that the class whose object is provided


as an argument contains show()…

Problem3: We can’t use abstract class here because it does not support
multiple inheritance.
Why Interfaces?
• We have Abstract classes…then what is the need of
Interfaces?

• To facilitate Multiple Inheritance


Solution is Interface
interface Showable
{
void show();
}

class Invoker
{
public static void invoke(Showable x)
{
x.show();
}
}
class A implements Showable
{
String name;
public A(String s)
{
name=s;
}
public void show()
{
System.out.println(“It is object:” + name);
}
}
class B implements Showable
{
int p;
public B(int x)
{
p=x;
}
public void show()
{
System.out.println(“value of p is:” + p);
}
}
Class InterfaceTest
{
public static void main(String arr[])
{
A m = new A(“Hello”);
B n = new B(10);
Invoker.invoke(m);
Invoker.invoke(n);
}
}
Default Method
• Java 8 introduces “Default Method” or (Defender methods)
new feature, which allows developer to add new methods to
the interfaces without breaking the existing implementation of
these interface.

• It provides flexibility to allow interface define implementation


which will use as default in the situation where a
concrete class fails to provide an implementation for
that method.
Why Default Method?
• Reengineering an existing JDK framework is always very
complex.

• Default methods enable to add new functionality to existing


interfaces without breaking older implementation of these
interfaces.

• Therefore, default methods have introduced as a mechanism to


extending interfaces in a backward compatible way.
Default Method
interface Demo
{
int a = 10; // public final static
void method1(); // public
default void method2() //public
{
System.out.println(“default method”);
}
}
Static Method
• Java interface static method is similar to default method
except that we can’t override them in the implementation
classes.

• This feature helps us in avoiding undesired results incase of


poor implementation in implementation classes. 
Static Method
interface Demo
{
int a = 10; // public final static
void method1(); // public abstract
default void method2() //public
{
System.out.println(“default method”);
}
static void method3()
{
System.out.println(“static method”);
}

}
Brain Storming Question

Is the following declaration for interface Bendable correct and free of


compilation error?
• abstract interface Bendable { // line 1
• final int x = 2009; // line 3
• void method1() ; // line 5
• public class Angle {} // line 6
• }
• choose only one answer:
• A) Yes, this is a correct and free of error declaration
• B) No, compilation error at line 1 , abstract should be removed
• C) No, compilation error at line 3 , x should be declared public final
• D) No, compilation error at line 6 , can't declare a class inside an interface
• Ans- A
Brain Storming Question

Is the following declaration for interface Bendable correct and free of


compilation error?
• abstract interface Bendable { // line 1
• final int x = 2009; // line 3
• void method1(); // line 5
• }
• choose only one answer:
• A) Yes, this is a correct and free of error declaration
• B) No, compilation error at line 1, Bendable should be declared public
abstract
• C) No, compilation error at line 3 , x should be declared public final
• D) No, compilation error at line 5 , method method1() should be declared
public abstract
• Ans- A
Brain Storming Question

• abstract interface Bendable { // line 1


• final int x = 2009; // line 3
• void method1(){}; // line 5
• }
• A) Yes, this is a correct and free of error declaration
• B) No, compilation error at line 1
• C) No, compilation error at line 3
• D) No, compilation error at line 5
• Ans-D
Brain Storming Question

• interface Movable {
• public abstract void m1(); // line 1
• void m2(); // line 2
• public void m3(); // line 3
• abstract void m4(); // line 4
• }
• class Chair implements Movable { // line 5
• public void m1() { } // line 6
• void m2() { } // line 7
• }
• choose all the answers that apply:
• A) mark class Chair "abstract"
• B) mark Chair "abstract" and mark m2() "public"
• C) implement m3() and m4() in Chair (with public access modifier)
• D) implement the methods m3() and m4() in Chair (with public access
modifier) and mark m2() in Chair "public“
• Ans-BD
Let’s Do It
• Create a interface Shape with abstract method area. Then
create two subclasses of Shape named as Square and
Rectangle. Write a test program to calculate area of Square
and Rectangle by using same reference variable of Shape.
Let’s Do It
• Create an abstract class named Book . Include a String field
for the book’ s title and a double field for the book ’s price.
Within the class, include a constructor that requires the book
title, and add two get methods —one that returns the title and
one that returns the price. Include an abstract method named
setPrice(). Create two child classes of Book : Fiction and
NonFiction . Each must include a setPrice() method that sets
the price for all Programming Books to $24.99 and for all
Math’s Books to $37.99. Write a constructor for each subclass,
and include a call to setPrice() within each. Write an
application demonstrating that you can create both a
Programming and a Math’s Book and display their fields.
Let’s Do It
• Create a interface SavingAccount with data member
numberOfTransaction (4) and methods deposit() & withdraw().
• Create interface CurrentAccount with data member
minimumAmount and methods deposit() & withdraw().
• Create a class PNB which deals with Current Accounts and
Saving Accounts with necessary members and interest rate 4%.
• Create a class SBI which deals with Current Accounts and Saving
Accounts with necessary members and interest rate 5%.
• Write a user interactive program to handle the accounts of any
number of customers of saving and current account in PNB and
SBI.
Let’s Do It
• Write an application named BookArray in which you create an
array that holds 10 Books, some Programming and some
Math’s. Using a enhanced for loop, display details about all 10
books.
Let’s Do It
• Create an interface named Turner, with a single method named
turn().
• Create a class named Leaf that implements turn() to display
“Changing colors”.
• Create a class named Page that implements turn() to display
“Going to the next page”.
• Create a class named Pancake that implements turn() to
display “Flipping”.
• Write an application named DemoTurners that creates one
object of each of these class types and demonstrates the turn()
method for each class.
Let’s Do It
Let’s Do It
Let’s Do It

Das könnte Ihnen auch gefallen