It’s possible to create the Object for the interface?
When working with smartcard project, I have come across the requirement to filter the only .doc file from a directory in a file array.
For that I have used the following classes and interfaces are:
1. File-Class
2. FileFilter-Interface.
I have created the Object for the FileFilter interface as below.
static FileFilter fileFilter=new FileFilter() {
public boolean accept(File pathname) {
System.out.println("with in accept");
String filename=pathname.getName();
if(filename.endsWith(".doc"))
{
return Boolean.TRUE;
}
return Boolean.FALSE;
// throw new UnsupportedOperationException("Not supported yet.");
}
};
Passed the file filter instance to the listFiles method of File class to get the only .doc file array.
as below.
File directory=new File("C:/Documents and Settings/Marimuthu/Desktop/download");
File[] filearray=directory.listFiles(fileFilter);
for(File docfile:filearray)
{
System.out.println("docfilename="+docfile.getName());
}
So finally I got the only File array that contains only doc files.
Code for File Filter:
public class SampleFileFilter{
static FileFilter fileFilter=new FileFilter() {
public boolean accept(File pathname) {
System.out.println("with in accept");
String filename=pathname.getName();
if(filename.endsWith(".doc"))
{
return Boolean.TRUE;
}
return Boolean.FALSE;
// throw new UnsupportedOperationException("Not supported yet.");
}
};
public static void main(String arg[])
{
File directory=new File("C:/Documents and Settings/Marimuthu/Desktop/download");
File[] filearray=directory.listFiles(fileFilter);
for(File docfile:filearray)
{
System.out.println("docfilename="+docfile.getName());
}
}
}
But it’s can’t be understandable by Beginners so I have created separate sample interface object.
Sample for Begineer:
Code for Interface:
package com.blogspot.microtechinfo.java.exploration;
/**
*
* @author Marimuthu
*/
public interface SampleInterface {
public void createObject();
}
Code for Class:
package com.blogspot.microtechinfo.java.exploration;
/**
*
* @author Marimuthu
*/
public class SampleClass {
/*Create Reference for the SampleInterface
*
*/
static SampleInterface sampleInterface=new SampleInterface() {
/////////Implementation of the createObject method.
public void createObject() {
System.out.println("Ya! Ya! Its possible to create Object for Interface");
//throw new UnsupportedOperationException("Not supported yet.");
}
};
public static void main(String arg[])
{
//////////Use the smapleInterface reference to call the create object method
sampleInterface.createObject();
}
}
Conclusion:
Finally we can create the object for the interface also.
machi this is a good articles for java beginners . great work!!
ReplyDeleteThanks da.. Saran...
ReplyDeletealways welcome ur feedback.
As per saran, we can create the object by creating anonymous class and we have to override the method.
ReplyDelete