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

Java Unit-3.2

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

Java Unit-3.2

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

Unit-3

Interfaces & Packages

1
Interfaces
• An interface, is a way of describing what classes
should do, without specifying how they should do
it.

• Interfaces are syntactically similar to classes, but


their methods are declared without any body.

• Any number of classes can implement an interface.

• One class can implement any number of interfaces.


2
Defining an Interface
• The general form of an interface:
access_specifier interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
} 3
• Here, access_specifier is either public or default.

• Variables can be declared inside of an interface, They are


implicitly static and final.
– They cannot be changed.
– They can be directly accessed by using interface name or
class name that implements interface.

• They must be initialized with a constant value.

• All methods and variables are implicitly public if the interface,


itself, is declared as public.

• Methods can not be declared as static or final.

4
Ex:-
interface Callback
{

void callback(int param);

5
Implementing Interfaces
• Once an interface has been defined, one or more classes can
implement that interface.

• The general form of a class that implements an interface.

access_specifier class classname [extends superclass]

[implements interface
[,interface...] ]
{

// class-body
6
• If a class implements more than one interface,
the interfaces are separated with a comma.

• The type signature of the implementing method


must match exactly the type signature specified
in the interface definition.

• When you implement an interface method, it


must be declared as public.

7
Example class that implements the Callback interface
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.

• Note: When you implement an interface method, it must be


declared as public.
8
• Classes that implement an interfaces can define additional
members of their own

Ex:-
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.");
}
}
9
Accessing Implementations Through Interface
References
• Any instance of any class that implements the
interface can be referred by an interface variable.

• When you call a method through an interface


variable, the correct version will be called based on
the actual instance of the class referred by the
variable.

• This is one of the key features of interfaces.

10
• 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);
}
}
Note : c can be used to access the callback( ) method,
but it cannot be used to access any other members of
the Client class. 11
Partial Implementations
• If a class does not fully implement the methods defined by
the interface, then that class must be declared as abstract.
Ex:-
abstract class Incomplete implements Callback
{
int a, b;
void show()
{ System.out.println(a + " " + b); }
// ...
}
• Any class that inherits Incomplete must implement
callback( ) or be declared abstract itself.

12
Variables in Interfaces
• You can use interfaces to share constants among classes by
simply declaring an interface that contains variables which are
initialized to the desired values.
Ex:-
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
13
Methods in Interfaces
• Methods are Just declared.

• Methods are not defined.

• Class which is implementing Interface


can define the methods

14
Interfaces Can Be Extended
• One interface can inherit another by use of the keyword
extends.

• The syntax is similar to 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, otherwise that class should be declared as
abstract class.

15
Ex:-An Application using interfaces
interface A public void meth3()
{ {
void meth1();
System.out.println("Implement
void meth2();
meth3().");
}
}
interface B extends A
{
}
void meth3(); class IFExtend
} {
class MyClass implements B public static void main(String arg[])
{ {
public void meth1()
MyClass ob = new MyClass();
{
ob.meth1();
System.out.println("Implement meth1().");
} ob.meth2();
public void meth2() ob.meth3(); O/P:
{ } Implement meth1().
System.out.println("Implement meth2()."); } Implement meth2().
} Implement meth3().
16
Use of implements and extends
keyword

• implements is used to implement the


interface (interface methods) by the class.

• extends is used to inherit one interface


from another interface (inherit one class from
another class).

17
Differences between classes and interfaces

• Interfaces has method declarations with out


any body
• Interfaces has instance variables with
constant values
• Classes has to implement the interfaces
• Instances can not be created for interfaces

18
Use of Interfaces
• It acts as APIs (Application Programming
Interface)
• It means users can implement interfaces in its
own way (depends on the application)
• It is easy to add new features (like members)
to the interfaces

19
Packages
• The main feature of OOP is its ability to support
the reuse of code:
– Using the classes ( directly )
– Extending the classes (via inheritance)
– Extending interfaces
• The features in basic form limited to reusing the
classes within a program

• What if we want to reuse your classes in other


programs without physically copying them ?

• In Java, this is achieved by using “packages”, a


concept similar to “class libraries” in other
languages 20
• Package is a group of classes
Creating and importing a user defined
package
1. Pick a name for your package

Ex : 1. mypackage
2. mypackage.util

– java recommends lower case letters to the


package names

21
2. Choose a directory on your hard drive as the
root of your class library

– You need a place on your hard drive to store your


classes
– I suggest you create a directory such as c:\
javaclasses
– This folder becomes the root directory for your
Java packages

22
3.Create subdirectories within the package root
directory for your package name

-- For example, for the package named mypackage.util,


create a directory named mypackage in the c:\javaclasses.
Then, in the mypackage directory, create a directory named
util. Thus, the complete path to the directory that contains the
classes for the mypackage.util package is c:\javaclasses\
mypackage\util

23
4. Add the root directory for your package to
the classpath environment variable

 Do not disturb any directories already listed in the


classpath

– For example, suppose your classpsath is already set to


this:
C:\Program Files\Java\jdk1.5.0_05\lib;

– Then, you modify it to look like this:


C:\Program Files\Java\jdk1.5.0_05\lib;c:\javaclasses

24
5. Save the files for any classes you want to be
in a particular package in the directory for
that package

-- For example, save the files for a class that belongs to

the mypackage.util package in


c:\javaclasses\mypackage\util

25
6. Add a package statement at the beginning of
each source file

• The package statement creates a package with specified name

• All classes declared within that file belong to the specified


package

• For example: package mypackage.util;

• The package statement must be the first non-comment statement


in the file

26
Ex:

package mypackage.util;
public class Sum
{
public int sumInt(int a[])
{

int s=0;

for(int i=0;i<a.length;i++)
{
s = s+a[i];
}

return s;
}
27
}
Contd..
import mypackage.util.*;
class PackageDemo
{
public static void main( String args[])
{
int x[] = {1,2,3,4,5};
Sum s = new Sum();
System.out.println(s.sumInt(x));
}
}

Note: This file can be compiled and executed from any


place

28
• In general, a Java source file can contain any (or all)
of the following four internal parts:

– A single package statement (optional).


– Any number of import statements (optional).
– A single public class declaration (required).
– Any number of classes private to the package
(optional).

29
Accessing Classes from Packages
• There are two ways of accessing the classes
stored in packages:

1. Using fully qualified class name


• java.lang.Math.sqrt(x);

2. Import package and use class name directly


• import java.lang.Math;
• Math.sqrt(x);

30
• Selected or all classes in packages can be
imported:

– import package.ClassName;
– import package.*;

31
Types of Packages

Package

Built-in User-defined

32
Built-In Packages

java

33
Built-in examples

• import java.util.Scanner;
--java.util package contains Scanner class (has
methods nextInt(), next(),…)

• import java.lang.Math;
--java.lang package contains Math class (has
methods sqrt(), floor(), …)

34
User-defined examples

• import mypackage.util.Sum;
--user defined package mypackage.util
contains Sum class

35

You might also like