Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Module-3 Part-B (interface) book notes

Uploaded by

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

Java Module-3 Part-B (interface) book notes

Uploaded by

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

JAVA moDULE 8-3 PART B

192 Part I: The Java Language


Tnterfoces
String name ;
double bal;

public Balance (String n, double b)


name n;

bal - b:

public void show() {


if (bal<0)
System. out .print ("- -> ")}
System. out.println (name + ": $ + bal);

As you can see, the Balance class is now public. Also, its constructor and its show()
method are public, too. This means that they can be accessed by any type of code outside
the MyPackpackage.For example, here TestBalanceimports MyPack and is then able to
make use of the Balance class:

import MyPack. *i

class TestBalance
public static void main(String args [J) {

/* Because Balance is public, you may use Balance


class and call its constructor. */
Balance test = new Balance ("J. J. Jaspers", 99.88) ;
test.show () ; // you may also call show ()

As an experiment,remove the public specifier from the Balance class and then try

compiling TestBalance. As explained,errors will result.

Anterfaces
Using the keyword interface, you can fully abstract a class' intetface from its imiplementation.
That is, using interface, you can specity what a class must do, but not howit does it. Interfaces

are syntactically similar to classes, but theylackinstance variables, and their methods are

declared without any body. In practice, this


means that you can dene interfaces that don't
make assumptions about how they are implemented. Once it is defined, any number of
dlasses canimplement an interface. Also, one class can implement any number of interfaces.

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


methods defined
the interface. However, each class the is free to determine details of its own implementation.
By providing the interface keyword, Java allows you to fully utilize the "one interface,
multiple methods" aspect of polymorphism.
and Interfaces 193
Chapter 9: Packages

at run time. Normally,


resolution
dynamic method tobe present
are designed to support need
from one class to
another, both classes
Interfaces
to be called
that the method
signaturesare
order for a method
in

at compile time
compatible. This
so the Java
requirement
compiler can check to ensure
by itself makes for astatic
in a system like this,
functionality
and nonextensible
gets pushed up higher
classing

and higher
I
PART

environment. Inevitably to more and more subclasses.


will be available
so that the mechanisms ofa method or
in the class hierarchy the definition
They disconnect
Interfaces
designed to avoid this problem.
are hierarchy from
are in a different
Since interfaces
hierarchy.
set of methods from the inheritance to implement
that are unrelated in terms of the class hierarchy
it is possible for classes
classes, is realized.
This is where the real power of
interfaces
the same interface.

for many applications that would


functionality that is required
NoTE Interfaces add most of the
inheritance in a language such as C++.
normally resort to using multiple

Definingan Interface
much a class. This is the general form of an interface:
An interface is defined like

access interface name


return-type method-namel(parameter-list);

return-type method-nane2(parameter-list);

type final-varnamel= value;


type final-varname2
= value;

return-type method-nameN(parameter-list);

type final-varnameN=value;

and the interface is only


When no access specifierincludedjthen
is default access results
When it is declared as
members of the package in which it is declared.
to other
available
can be used by any
In this case, the interface must be the
other code.
public,the interface name as the interface.
the file, and the file must have the same
only public interface declared in
can any valid identifier. Notice that themethods that
name is the name of the interface, and
be

after the parameter list. They are,


are declared havelno bodies.They end with a semicolon
no default implementationof any
method specified
essentially abstract methodsjthere carn be
the methods.
an interface must implement all of
within an interface. Each cass that includeš And
declarations, They are implicitlyfinal
Varíables can be declared inside of interface
a lso be
implementing class, They must
static meaning they cannot be changedby the
are implicitly public.|
initialized) All methods and variables
It declares a simple interface that contains
Here is an example of an interface definition.
that takes a single integer parameter.
one method called callback()

{
interface Callback
;
void callback (int param)
94 Part I: The Java
Language

ImplementingInterfaces
Once an interface has been defined, one or more classes
implementan interface, include theimplements canimplement that interface.[lo
the methods defined bythe clause in a class definition, and ther
create
interface. The general form of a class that includes
clause looks like this: the implements

class classname
1/class-body
[extendssuperclass] [implements
interface [,interface..] |
It implements more than one interface, the interfaces are separated
aclass
with a comma.If
a class implementstwo 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.
Here is a small example class that implements the Callback interface shownearlier.

class Client implements Callback {


// Implement Callback's interface
public void callback(int p)

System.out.println ("callback called with + p):

Notice that callback()is declared using the public access specifier.

REMEMBER When you implement an interface method, it must be declared as public.

It isboth permissible and common for classes that implenmentinterfaces to define


additional members of their own. For example, the following version of Client implements
callback() and adds the method nonIfaceMeth( ):

class Client implements Callback {


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

void nonIfaceMeth () {
System.out.println ("Classes that implement interfaces "
" may also define other members, too. ");
Chapter 9: Packages and Interfaces 195

References
Accessing Implementations Through Interface
that use an interface rather than a class type.
You can declare variables as object references to by such
the declared interface can be referred
Any instance of any class that implements the correct version will
through one of these references,
a variable. When you call a method
the being referred to. This is one of the PARTI
be called based on the actual instanceof
interface

is looked up dynamically at run


time,
key features of interfaces. The method to be executed
methods on them. The calling
allowing classes to be created later than thecode which
calls

having to know anything about the "callee."


code can dispatch through an interface without
to using a superclass reference to access a subclass object, as described
This process is similar
in Chapter 8.

when
CAUTION Becausedynamic lookup of a method at run time incurs a significant overhead
not to use
compared with the normal method invocation in Java, you should be careful
interfaces

casually in performance-critical code.

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

class TestIface {

public static void main (String args []) {

Callback c = new Client (0;


c.callback (42) ;

The output of this program is shown here:

callback called with 42

is declared to be of the interface


Notice that variable c type Callback, yet it was assigned an
Although c can be used to access the callback()method, it cannot access
instance of Client.
has knowledge
any other membersof the Client class. An interface reference variable only
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

the polymorphic power of


can access an implementation object, it does not demonstrate
usage, the second implementation of Callback,
such a reference. To sample this first create

shown here:

dIAnother implementation of Callback.


class Anotherclient implements Callback {

// Implement Callback's interface


public void callback (int p)
{

of callback");
System. out.println ("Another version
System. out.println ("p squared
is " + (p*p)) ;
96 Part I: The Java Language

Now,try the following


class:
class TestIface2
public static void main
(String args []) {
Callback c new Client ():
Anotherclient ob new AnotherClient ()

c.callback (42);

C= ob; //
c now refers to AnotherClient
object
c.callback (42);

The output from this program is shown here:

callback called with 42


Another version of callback
p squared is 1764

As youcan see, the version of callback() that is called is determined by the type of object
that c refers to at run time. While this is a very simple example,you will see another, more
practical one shortly.

Partial Implementations
Ifa class includes an interface but does not fully implement the methods definedby that
interface, then that class must be declared as abstract. For example:

abstract class Incomplete implements Callback {


int a, b;
void show () {
System.out .println (a + n + 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
Aninterface can be declared a member of a class or another interface. Such an interface is

called a muember interfacelora nested interface.JA nested interface can be declared as public,
private, or protected. This differs from top-level interface, which must either be declared

as(publigoruse theefaultaccess 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 membe. Thus, outside of the class or interface in which a nested interface is
declared, its name must be fully qualified.
Here is arn example that demonstrates a nested interface:

// A nested interface example.

// This class contains a member interface.


class A{
Chapter 9: Packages and Interfaces 197

1/ thia ia a neated interface


public interface NeatedIP (
boolean iøNotNegat ive (int x)

1/ B implement the nested PARTI

class B implement s A,NestedIF1nterface.


{
public boolean iøNotNegative (int
return x « 0 ? falBe : true;
x)(

class NeštedIFDemo {
public static void ma in
(String args []) {
// use a nested interface reference
A,NestedIF nif new B();

if (nif.isNotNegat ive(10))
System. out.println("10 is not negative");
if (nif.isNotNegative (-12))
System.out .println("this won't be
displayed" );

Notice that A defines a member interface called NestedIF and that it is declared public.
Next, B implementsthe 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
Bobject. Because B implements
A.NestedIE, this is legal.
Interfaces Can Be Extended
One interface carn inheritanother by use of the keyword extends. The syntax is the same as
for inheriting classes. When implements an intertace that inherits another interface,
a class

it must provide implementations for all methods defined within the interface inheritance

)
chain. Following is an example:

1/ One interface can extend another.


interface A { ACvdenface
void methl () :
void meth2 ();

// B includes meth1() and meth2 () -- it adds meth3 ().


now
(intea)
interface Bextends |A {
void meth3 ()i
A
1 This class must implement all of A and B tetace B extus
class MyClass implements B{
public void methl () {
System. out .println ("Implement methi () .");

public void meth2 () {

() ."):
System.out.println ("Implement meth2

public void meth3 () {


Packages and Interfaces 203
Chapter 9:

ln (" Implement meth3 ()."):


System. out.print

PARTI

class IFExtend {
public static void main (Sting arg []) {

MyClass ob = new MyClass ():

ob.methi () ;
ob.meth2 ()
ob.meth3 () ;

the implementation for mneth1() in


As an experiment, you might want to try removing
MyClass. This will cause a compile-time error. As stated earlier, any class that implements

must implement methods defined by that interface, including any that are
an interface all

inherited from other interfaces.

Although the examples we've included in this bookdo not make frequent use of packages
or interfaces, both of these tools are an important part of the Java programmingenvironnment.
all real programs that you write in Java will be contained within packages. A number
Virtually

will probably implement interfaces as well. It is important, therefore, that you be comfortable
with their usage.

olP Tmend rth1().


Tmlement nethe().
slotic
thols in Date FABER-CASTELI
Use Page No.
teaface

interlaco Neonteface

vel he lloc)
stodic

sttc
Syotemoteprid(" kello,dsom
3
vaio eyeni eMetthoo(Sting

lass ntefqce

Ssdeodpinslalstr)

lessDeme

Itenfqce rtfqce

vtegov)f oves se Me-fho dHello,ove methao

ol22Hello,rurn sothc medto


le oveemethod.

You might also like