0% found this document useful (0 votes)
8 views43 pages

9_Interfaces

The document provides an overview of interfaces in Java, explaining how they allow for the abstraction of class functionality and support polymorphism. It covers the definition, implementation, and usage of interfaces, including nested interfaces, variables in interfaces, and the introduction of default and static methods in JDK 8. Additionally, it addresses issues related to multiple inheritance and conflict resolution when implementing multiple interfaces with default methods.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views43 pages

9_Interfaces

The document provides an overview of interfaces in Java, explaining how they allow for the abstraction of class functionality and support polymorphism. It covers the definition, implementation, and usage of interfaces, including nested interfaces, variables in interfaces, and the introduction of default and static methods in JDK 8. Additionally, it addresses issues related to multiple inheritance and conflict resolution when implementing multiple interfaces with default methods.

Uploaded by

sindhus121985
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

1

Module 3
Interfaces
CHAPTER 9
Interfaces 2

• Using the keyword interface, you can fully abstract a


class’s interface from its implementation.
• That is, using interface, you can specify what a class must
do, but not how it does it.
• Interface are syntactically similar to classes, but they lack
instance variable and their methods are declared without any
body.
Interfaces
3
 i.e can define interfaces that don’t make assumptions about how
they are implemented.
 Once it is defined, any number of classes can implement an
interface.

 To implement an interface, a class must create the complete set of


methods defined by the interface.
 each class is free to determine the details of its own
implementation.
• “one interface, multiple methods” So it points to polymorphism
feature of java.
Interfaces
4
Defining an Interface
• Interfaces are designed to support dynamic method resolution at run5time.

When no access specifier is included, then default access results, and the
interface is only available to other members of the package in which it is
declared.
Contd…
• 6 other
When it is declared as public, the interface can be used by any
code.
• In this case, the interface must be the only public interface declared in
the file, and the file must have the same name as the interface.

• name is the name of the interface, and can be any valid identifier. Notice
that the methods that are declared have no bodies.

• Variables can be declared inside of interface declarations. They are


implicitly final and static, meaning they cannot be changed by the
implementing class.

• They must also be initialized. All methods and variables are implicitly
public.
Contd…
7
Contd…
8
Contd… 9

• Ex: It declares a simple interface that contains one method called


callback( ) that takes a single integer
interface Callback
{
void callback(int param);
}
Contd…
10
Implementing Interfaces 11

 Once an interface has been defined, one or more classes can


implement that interface.

 To implement an interface, include the implements clause in a class


definition, and then create the methods defined by the interface.

 A class must create complete set of methods defined by the


interface
 Each class can have its implementation
Implementing Interfaces 12

Genral form:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

class xyz implements abc


{
// Implement abc interface
}

class exp implements abc


{
// Implement abc interface
“One Interface, Multiple Methods” }
Implementing Interfaces 13

• If a class implements more than one interface, the interfaces are


separated with a comma.

• If a class implements two interfaces that declare the same method,


then the same method will be used by clients of either interface.

• The methods that implement an interface must be declared public.

• Also, the type signature of the implementing method must


match exactly the type signature specified in the interface
definition.
Example
14
Interface methods to be implemented as public only

interface Callback
{
void callback(int param);
}

class Client implements Callback


{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
Example
15

class Client implements Callback


{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
} Each class can have its own
void nonIfaceMeth( )
implementation
{
System.out.println("Classes that implement interfaces " + "may
also define other members, too.");
}
}
Accessing Implementations Through Interface References
16
• You can declare variables as object references that use an interface
rather than a class type.
• Any instance of any class that implements the declared interface can be
referred to by such a variable.
• When you call a method through one of these references, the correct
version will be called based on the actual instance of the interface being
referred to.
• This is one of the key features of interfaces.
• The method to be executed is looked up dynamically at run time,
allowing classes to be created later than the code which calls methods
on them.
Accessing Implementations Through Interface References

17
•The following example calls the callback( ) method via an interface
reference variable:

class TestIface
{
public static void main(String args[ ])
{
Callback c = new Client();

c.callback(42);
}
}

The output of this program is shown here:


callback called with 42
Contd…
18
 Notice that variable c is declared to be of the interface type Callback,
yet it was assigned an instance of Client.
 Although c can be used to access the callback( ) method, it cannot
access any other members of the Client class.
 An interface reference variable only has knowledge of the methods
declared by its interface declaration.
 Thus, c could not be used to access nonIfaceMeth( ) since it is defined
by Client but not Callback.
 While the preceding example shows, mechanically, how an interface
reference variable can access an implementation object, it does not
demonstrate the polymorphic power of such a reference.
Example
// Another implementation of Callback.
class AnotherClient implements Callback
19
{
// Implement Callback's interface
public void callback(int p)
{
System.out.println("Another version of callback");
System.out.println("p squared is " + (p*p));
}
}
class TestIface2
{
public static void main(String args[ ])
{ callback called with 42
Another version of callback
Callback c = new Client( );
p squared is 1764
AnotherClient ob = new AnotherClient( );
c.callback(42);
c = ob; // c now refers to AnotherClient object
c.callback(42);
}
}
Partial Implementations 20
 If a class includes an interface but does not fully implement the methods defined
by that interface, then that class must be declared as abstract.

abstract class Incomplete implements Callback


{
int a, b;
void show( )
{
System.out.println(a + " " + b);
}
// ...
}

 Here, the class Incomplete does not implement callback( ) and must be
declared as abstract. Any class that inherits Incomplete must implement
callback( ) or be declared abstract itself.
Nested Interfaces
21
 An interface can be declared a member of a class or another interface.
Such an interface is called a member interface or a nested interface.

 A nested interface can be declared as public, private, or protected.

 This differs from a top-level interface, which must either be declared


as public or use the default access level, as previously described.

 When a nested interface is used outside of its enclosing scope, it must


be qualified by the name of the class or interface of which it is a
member.
Nested Interfaces
 Thus, outside of the class or interface in which a nested interface
22 is
declared, its name must be fully qualified.
// A nested interface example.
// This class contains a memberinterface. class NestedIFDemo
class A {
{ public static void main(String args[ ])
public interface NestedIF {
{ // use a nested interface reference
boolean isNotNegative(int x); A.NestedIF nif = new B( );
}
} if(nif.isNotNegative(10))
// B implements the nested interface. System.out.println("10 is not negative");
class B implements A.NestedIF {
public boolean isNotNegative(int x) if(nif.isNotNegative(-12))
{ System.out.println("this won't be displayed");
return x < 0 ? false : true; }
} }
}
Contd…
23

 Notice that A defines a member interface called NestedIF and


that it is declared public. Next, B implements the nested
interface by specifying
implements A.NestedIF
 Notice that the name is fully qualified by the enclosing class’ name.
Inside the main( ) method, an A.NestedIF reference called nif is
created, and it is assigned a reference to a B object.
Variables in Interfaces
25
 You can use interfaces to import shared constants into multiple classes
by simply declaring an interface that contains variables that are
initialized to the desired values.
 When you include that interface in a class (that is, when you
“implement” the interface), all of those variable names will be in
scope as constants.
 If an interface contains no methods, then any class that includes such
an interface doesn’t actually implement anything.
 It is as if that class were importing the constant fields into the class
name space as final variables.
Variables in Interfaces
26
• Consider an Example: AskMe.java
• Notice that this program makes use of one of Java’s standard classes:
Random. This class provides pseudorandom numbers.
• It contains several methods that allow you to obtain random numbers
in the form required by your program. In this example, the method
nextDouble( ) is used. It returns random numbers in the range 0.0
to 1.0
• In this sample program, the two classes, Question and AskMe, both
implement the SharedConstants interface where NO, YES,
MAYBE, SOON, LATER, and NEVER are defined.
Variables in Interfaces 27

import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
AskMe.java
class AskMe implements SharedConstants {
class Question implements static void answer(int result) {
SharedConstants { switch(result) {
Random rand = new Random(); case NO:
System.out.println("No");
int ask() {
break;
int prob = (int) (100 *rand.nextDouble());
case YES:
if (prob < 30) System.out.println("Yes");
return NO; // 30% break;
else if (prob < 60) case MAYBE:
return YES; // 30% System.out.println("Maybe");
else if (prob < 75) break;
return LATER; // 15% case LATER:
else if (prob < 98) System.out.println("Later");
return SOON; // 13% break;
case SOON:
else
System.out.println("Soon");
return NEVER; // 2% break;
} case NEVER:
} System.out.println("Never");
break;
}
}
AskMe.java
29

public static void main(String args[]) {


Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
Interfaces Can Be Extended
30
 One interface can inherit another by use of the keyword extends. The
syntax is the same as for inheriting classes.
 When a class implements an interface that inherits another interface, it must
provide implementations for all methods defined within the interface
inheritance chain.
public void meth2( ) {
// One interface can extend another. System.out.println("Implement meth2( ).");
interface A { }
void meth1( ); public void meth3( ) {
void meth2( ); System.out.println("Implement meth3().");
} }
// B now includes meth1() and meth2() -- it adds meth3 ( ).
}
interface B extends A {
class IFExtend {
void meth3( );
public static void main(String arg[]) {
}
MyClass ob = new MyClass();
// This class must implement all of A and B
ob.meth1();
class MyClass implements B {
ob.meth2();
public void meth1( ) {
ob.meth3();
System.out.println("Implement meth1( ).");
}
}
}
Contd…
31

• As an experiment, you might want to try removing the implementation

for meth1( ) in MyClass. This will cause a compile-time error. As

stated earlier, any class that implements an interface must

implement all methods defined by that interface, including that

are inherited from other interfaces.


Default Interface Methods
 prior to JDK 8, an interface could not define any implementation. This
meant that for all previous versions of Java, the methods specified by
an interface were abstract, containing no body.

 This is the traditional form of an interface and is the type of interface


that the preceding discussions have used.

 The release of JDK 8 has changed this by adding a new capability to


interface called the default method. A default method lets you define
a default implementation for an interface method.

 In other words, by use of a default method, it is now possible for an


interface method to provide a body, rather than being abstract.

 During its development, the default method was also referred to as an


extension method, and you will likely see both terms used.
Default Method Fundamentals
 An interface default method is defined similar to the way a
method is defined by a class.
 The primary difference is that the declaration is preceded
by the keyword default. For example, consider this simple
interface:
Multiple Inheritance Issues
 Java does not support the multiple inheritance of classes.

 Now that an interface can include default methods, you


might be wondering if an interface can provide a way
around this restriction.

 The answer is, essentially, no. Recall that there is still a key
difference between a class and an interface: a class can
maintain state information (especially through the use of
instance variables), but an interface cannot.
 default methods do offer a bit of what one would normally
associate with the concept of multiple inheritance.

 For example, you might have a class that implements two


interfaces. If each of these interfaces provides default
methods, then some behavior is inherited from both.

 Thus, to a limited extent, default methods do support


multiple inheritance of behavior.

 As you might guess, in such a situation, it is possible that a


name conflict will occur.
example
 assume that two interfaces called Alpha and Beta are
implemented by a class called MyClass.

 What happens if both Alpha and Beta provide a method


called reset( ) for which both declare a default
implementation? Is the version by Alpha or the version by
Beta used by MyClass? Or, consider a situation in which
Beta extends Alpha.

 Which version of the default method is use ? Or, what if


MyClass provides its own implementation of method?

 To handle these and other similar types of situations, Java


defines a set of rules that resolves such conflicts.
First, in all cases,

A class implementation takes priority over an interface


default implementation. Thus, if MyClass provides an
override of the reset( ) default method, MyClass’ version is
used. This is the case even if MyClass implements both
Alpha and Beta. In this case, both defaults are overridden
by MyClass’ implementation.
Second,

In cases in which a class implements two interfaces that


both have the same default method, but the class does
not override that method, then an error will result.

Continuing with the example, if MyClass implements


both Alpha and Beta, but does not override reset( ),
then an error will occur
Use static Methods in an Interface
 JDK 8 added another new capability to interface: the ability to

define one or more static methods.

 Like static methods in a class, a static method defined by an

interface can be called independently of any object. Thus, no

implementation of the interface is necessary, and no instance of

the interface is required, in order to call a static method.

 Instead, a static method is called by specifying the interface name,

followed by a period, followed by the method name. Here is the

general form:

 InterfaceName.staticMethodName
Example

One last point:


static interface methods
are not inherited by
either an implementing
class or a subinterface.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy