Вы находитесь на странице: 1из 19

OO Concepts: Intefaces

Atul Gupta

Interface






An interface is a data type (reference) in Java


A Java interface is a collection of constants and abstract
methods
All methods in an interface are abstract by default
An interface is used to identify a set of methods that a
class will implement
An implementing class must implement all methods
defined in the interface
Objects can have multiple types: the type of their own
class and the types of all the interfaces that they
implement

Defining an Interface
public interface GroupedInterface extends Interface1,
Interface2, Interface3
{
// constant declarations

double E = 2.718282; // base of natural logarithms


// method signatures

void doSomething (int i, double x);


int doSomethingElse(String s);
}

Comparable Interface in Java




The Comparable interface contains one abstract method


called compareTo, which is used to compare two
objects
Any class can implement Comparable to provide a
mechanism for comparing objects of that type
if (obj1.compareTo(obj2) < 0)
system.out.println ("obj1 is + less than obj2");

The value returned from compareTo should be negative


is obj1 is less that obj2, 0 if they are equal, and positive
if obj1 is greater than obj2

An Example
public class Employee implements Comparable {
int EmpID;
String Ename;
double Sal;
static int i;
public Employee() {
EmpID = i++;
Ename = "dont know";
Sal = 0.0;
}

public int compareTo(Object o1) {


if (this.Sal == ((Employee) o1).Sal)
return 0;
else if ((this.Sal) > ((Employee) o1).Sal)
return 1;
else
return -1;
}
}

public Employee(String ename, double sal) {


EmpID = i++;
Ename = ename;
Sal = sal;
}
public String toString() {
return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
}

Implementing Stack Interface

public interface StackInterface {


boolean empty();
void push(Object x);
Object pop() throws
EmptyStackException;
Object get() throws
EmptyStackException;
}

public class Stack implements StackInterface {


private Vector v = new Vector();
public boolean empty() {
return v.size() == 0;
}
public void push(Object item) {
v.addElement(item);
}
public Object pop() {
Object obj = this.get();
v.removeElementAt(v.size() - 1);
return obj;
}
public Object get() throws EmptyStackException {
if (v.size() == 0)
throw new EmptyStackException();
return v.elementAt(v.size() - 1);
}
}

Implementing Stack through Hierarchy?


public class Stack extends Vector {
public boolean empty() { return this.size() == 0;}
public Object push(Object item) {this.addElement(item); return item;}
public Object pop() {
Object obj;
int len = this.size();
obj = this.get();
this.removeElementAt(len - 1);
return obj;
}
public Object get() {
int len = size();
if (len == 0) throw new EmptyStackException();
return this.elementAt(len - 1);
}
}

Rewriting Interfaces
public interface DoIt {
void doSomething(int i, double x);
int doSomethingElse(String s);
}

public interface DoIt {


void doSomething(int i, double x);
int doSomethingElse(String s);
boolean didItWork(int i, double x,
String s);
}

public interface DoItPlus extends DoIt {


boolean didItWork(int i, double x, String s);
}

Interface Methods


The method modifiers are implicitly public and so can


have no other access modifier.
They cannot have modifiers that define implementation
characteristics such as native, synchronized, or strictfp
because an interface does not dictate implementation.
They cannot be final because they haven't been
implemented yet.
They can never be static because static methods can't be
abstract.

Interface vs. Abstract Class




Methods of a Java interface are implicitly abstract and


cannot have implementations. A Java abstract class can
have instance methods that implements a default behavior.
Variables declared in a Java interface is by default final. A
Java abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java
abstract class can have the usual flavors of class members
like private, protected, etc..
Java interface should be implemented using keyword
implements; A Java abstract class should be extended
using keyword extends.

Interface vs. Abstract Class




An interface can extend other Java interfaces, an


abstract class can extend another Java class and
implement multiple Java interfaces.
A Java class can implement multiple interfaces but it
can extend only one abstract class.
Interface is absolutely abstract and cannot be
instantiated; A Java abstract class also cannot be
instantiated, but can be invoked statically.
In comparison with java abstract classes, java interfaces
are slow as it requires extra indirection.

Interface vs. Class




An interface is an expression of pure design, whereas a


class is a mix of design and implementation.
the classes that are extended and the interfaces that are
implemented are collectively called the supertypes.

Java Collection Framework (JCF)




Provides a well-designed set of interfaces and classes


for storing, sorting and manipulating groups of data as a
single unit, a collection
Made up of a set of interfaces for working with the
groups of objects.

The Iterator Interface




An iterator is an object that provides a means of


processing a collection of objects one at a time
An iterator is created formally by implementing the
Iterator interface, which contains three methods





The hasNext() method returns a boolean result true if there are


items left to process
The next() method returns the next object in the iteration
The remove() method removes the object most recently
returned by the next method

The Collection Interfaces







Collection<E> The root interface for collections. Provides such methods as add,
remove, size, and toArray.
Set<E> A collection in which no duplicate elements can be present, and whose
elements are not necessarily stored in any particular order (extends Collection<E>).
SortedSet<E> A set whose elements are sorted (extends Set<E>).
List<E> A collection whose elements stay in a particular order unless the list is
modified (extends Collection<E>). This is a general use of the word "list" and does not
necessarily mean "linked list," although that is one possible implementation.
Queue<E> A collection with an implied ordering in its elements (extends
Collection<E>). Every queue has a head element that is the target of specific operations
like deque and enqueue.
Iterator<E> An interface for objects that return elements from a collection one at a
time. This is the type of object returned by the method Iterable.iterator.
ListIterator<E> An iterator for List objects that adds useful List-related methods. This
is the type of object returned by List.listIterator.
Iterable<E> An object that provides an Iterator and so can be used in an enhanced for
statement.

Map Interfaces


Map<K,V> A mapping from keys to at most one value each. (Map does not
extend Collection, although the concepts meaningful to both maps and
collections are represented by methods of the same names, and maps can be
viewed as collections.)
SortedMap<K,V> A map whose keys are sorted (extends Map<K,V>).

Concrete Implementation java.util




HashSet<E> A Set implemented as a hashtable. A good, generalpurpose implementation for which searching, adding, and removing are
mostly insensitive to the size of the contents.
TReeSet<E> A SortedSet implemented as a balanced binary tree.
Slower to search or modify than a HashSet, but keeps the elements
sorted.
ArrayList<E> A List implemented using a resizable array. It is
expensive to add or delete an element near the beginning if the list is
large, but relatively cheap to create and fast for random access.
LinkedList<E> A doubly linked List and Queue implementation.
Modification is cheap at any size, but random access is slow.
HashMap<K,V> A hashtable implementation of Map. A very
generally useful collection with relatively cheap lookup and insertion
times.
TreeMap<K,V> An implementation of SortedMap as a balanced
binary tree to keep its elements ordered by key. Useful for ordered data
sets that require moderately quick lookup by key.

Interface Summary





Interfaces are similar to classes with one major difference: Can


not be instantiated!
Interfaces are used to decouple specification from
implementation
Interfaces in Java can be used to implement multiple inheritance
Interface or Abstract Class? The decision depends on many
factors
Interfaces can also be involved in a hierarchy with other classes
and interfaces
An object of a class implementing an interface is of both types: of
the type of the class as well as of the interface

Вам также может понравиться