Common Interfaces in Java

0
598
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Any class that contains methods of these names(written below) is said to implement the Enumeration interface. We can say StringTokenizer class implements this interface.The enum typevalues are referred as enum constants hence the values are made up with uppercase letters. This is a style but not syntax.

Exp:
for printing all elements of a vector myVec:

interface Enumeration{
public boolean hasMoreElements();
public Object nextElement();
}
for(Enumeration e=myVec.elements();
e.hasMoreElement())
{
System.out.println(e.nextElement());
} 

The vector,Hashtable and HashMap classes all have an elements method which returns an Enumeration Objects.The enum definition should not be part of any function including main method. This have to be defined outside of the method.This is popular Interface example in java.

The interface Enumeration looks below:

public interface java.util.Enumeration{
//methods:
public abstruct boolean hasMoreElements();
//returns true if the enumeration contains more elements and returns false 
//if the enumeration contains no elements
public abstruct Object nextElement()
//returns the next element of this enumeration. It can throw NoSuchElementException 
//if there is not element present.
}

An Example:

Vector v=new Vector();
v.add("Apple");
v.add("Grapes");
v.add("Banana");
Enumeration enum=v.elements();
while (enum.hasMoreEmenets())
{
String s=(String)enum.nextElement();
System.out.println(s);
}

An enum is technically a class so the enum values are objects of that class.They also contain methods called ordinal(). When used with an enum,the ordinal() method returns the position of the enum object in the list.


enum Browser{IE,FF,Chrome}
Browser browserIE=Browser.IE;
Browser browserFF=Browser.FF;
Browser browserChrome=Browser.Chrome;
Browser.FF.ordinal();//returns 2
 

A unit of collection of data items is called data structure.Example List(a sequence of items)
enhanced for loop can be used as below:


for((enum-type-name)(variable name):(enum-type-name).values()){{
statement
}
//like
enum Days{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}
for(Days d:Days.values())
{
System.out.println(d);
System.out.println(d.ordial());
}
 

Enhanced for loop is to do something “for each” item in a data structure,it is often called for each loop.like for each Days d in Days.values()
: menas in.
The method clone() duplicates the class vector not the objects it holds.Since clone is a method of Object class,many classes are cloneable.

Another Example:

class EnumeratorTest{
public static void main(String args[]){
Vector v=new Vector();
v.addElement(new file("."));
v.addElement(new Vector());
v.addElement(new EnumeratorTest());
v.addElement(new Date());
//class object represents a class itself.
Hashtable h=new Hashtable();
h.put(new Integer(1),new Thread());
h.put(new Integer(2),new ProtocolException().getClass().getSuperClass());
h.put(new Integer(3),v.clone());
}

Note that the only thing common between containers is that they contain only class object.Now if we to keep a specific type in that case Enumeration is the key.However we need to downcast Object to the particular type.This is popular Interface example in java.

Interface Cloneable in Java

A class that implements the Cloneable interface,indicates to the clone() method in the class Object that it is legal for that method to make a field for field copy of instances of that class. Any attempt to clone instances that do not implement the cloneable interface results in the exception- CloneNotSupportedException being thrown.
The structure is given below:


public interface java.lang.Cloneable{
}
 

Runnable interface in Java:

The runnable interface should be implemented by any class whose instances are intended to be executed by a thread(a sub class of Thread class). The class must define a method called run() in its body. run() method has no argument.Any class that implements this interface can provide the body of a thread inside run method.

The structure of the Runnable interface is given below:


public interface java.lang.Runnable{
//Method:
public abstract void run();
}
 

When an object implements Runnable interface, it creates a thread.To start the thread,Object’s start() method is called from a separate thread.(Calling thread).

If mt is an instance of Thread, then mt.start() and mt.run() are two different things.Calling mt.run() will execute the run() method in the same thread which is calling this method. It won’t create a new thread. On the other hand if mt.start() is called , it creates a new thread and execute the things in the new thread. So if any preconditions are there before the run() method will be ignored if only mt.run() is called.This is popular Interface example in java.

Interface FilenameFilter in Java:

Instance of classes which implement this interface are used to filter filenames. These instances are used to filter directory listing in the list method of class File(Class File,Utility) and by the abstract window toolkit’s file dialog components.This method defines the accept() method that needs to be implemented by any object that filters filenames.There is no standard FinenameFilter classes in java but objects that implement this interface are used by FileDialog object or File.list() method.It checks for the file or the extension.
So this object can be passed to File.list(), FileDialog.setFilenameFilter(), FileDialogPeer.setFilenameFilet() these method also this object is returned by FileDialog.getFilenameFilter().

The structure of the Interface FilenameFilter is given as:

public interface java.io.FilenameFilter{
//method
public abstract boolean accept(File dir,String name);
//Determines whether a specified file should be included in a file list.
//Returns true if the name should be included in file list,false otherwise.
} 

Interface ContentHandlerFactory in Java

ContentHandlerFactory interface defines a factory for content handlers.This interface is used by the URLSTREAMHandler class to create a content handler for a MIME type.An implementation of this interface should map a mime type into an instance of content handler.

The structure of the interface ContentHandlerFactory is given as:


public interface java.net.ContentHandlerFactory{
//methods
public abstract ContentHandler createContentHandler(String mmeType);
//creates a new ContentHandlerFactory instance ti read an object from a URLStreamHandler.
}

Interface FilenameFilter in Java:

Instance of classes which implement this interface are used to filter filenames. These instances are used to filter directory listing in the list method of class File(Class File,Utility) and by the abstract window toolkit’s file dialog components.This method defines the accept() method that needs to be implemented by any object that filters filenames.There is no standard FinenameFilter classes in java but objects that implement this interface are used by FileDialog object or File.list() method.It checks for the file or the extension.
So this object can be passed to File.list(),FileDialog.setFilenameFilter(),FileDialogPeer.setFilenameFilet() these method also this object is returned by FileDialog.getFilenameFilter().

The structure of the Interface FilenameFilter is given as:

public interface java.io.FilenameFilter{
//method
public abstract boolean accept(File dir,String name);
//Determines whether a specified file should be included in a file list.
//Returns true if the name should be included in file list,false otherwise.
} 

Interface ContentHandlerFactory in Java

ContentHandlerFactory interface defines a factory for content handlers.This interface is used by the URLSTREAMHandler class to create a content handler for a MIME type.An implementation of this interface should map a mime type into an instance of content handler.

The structure of the interface ContentHandlerFactory is given as:


public interface java.net.ContentHandlerFactory{
//methods
public abstract ContentHandler createContentHandler(String mmeType);
//creates a new ContentHandlerFactory instance ti read an object from a URLStreamHandler.
}

Interface PopupMenuPeer in AWT in Java:

The PopupMenuPeer Interface specifies the methods that all implementations of Abstract Window Toolkit must define while working with PopupMen
The hierarchy of calling this component is as follows:
[PopupMenuPeer(MenuPeer(MenuItemPeer(MenuComponentPeer)))]

The architecture of the interface PopupMenuPeer is given as :


public abstract interface java.awt.peer.PopupMenuPeer extends java.awt.peer.MenuPeer{
//methods:
public abstract void show(Event evt);
}

All About the SortedSet Interface in Collection In java:

The SortedSet interface is used to sort elements of a collection in ascending order.The SortedSet interface extends Set interface which in turn extends Collection Interface.The SortedSet interface does not allow duplicate elements in a Set.

The below methods are extra apart from Set Interface:

comparator();// Returns the comparator object.If the elements in the SortedSort are in ascending order
//then it returns null.
first();//Returns the first element of the SortedSet.
headSet(Object toElement);//Returns the number of elements less than that of the elements specified
//using toElement object.The elements are returned from the SortedSet.
last();//returns the last element from the SortedSet.
subSet(Object fromElement,Object toElement);//returns the elements between the range specified.
tailSet(Object fromElement);//returns the elements from a SortedSet that are greater than or equal 
//to fromElement. 

All About Queue Interface in Collection in Java

The Queue interface extends to Collection interface and declares the behavior of a queue. It is often first in first out list. In a queue ,elements can only be removed from head of that queue.

The method available in a Queue interface are:

element();//returns the element at the head of the queue.The element is not removed.
offer(Object obj);//attempts to add an element to the queue.Returns true if added,false otherwise.
peek();//returns the element at the head of the queue.The element is not removed.
poll();//returns the element at the head of the queue after removing the current head.
remove();//returns the element at the head of the queue after removing the element. 

The method element() and peek() are similar. If the queue is empty element() throws NoSuchElementException while peek() returns null.
The method poll() and remove() are also similar. poll() returns null when the queue is empty and remove() throws NoSuchElementException.

Iterator Interface in Java:

The Iterator interface(added in java-2) has the same effect and style as the Enumerated interface.It enables us to sequentially traverse and access the elements contained in a collection.The elements of a collection can be accessed using the method defined by Iterator interface.It proves easy methods like add() and remove() to add and remove items.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here