Friday, May 21, 2010

How to call a method in a public interface in Java?

Dear all:





I met a problem about how to call a method I need from a public interface in Java.What I've done in JCreator are:





1


Defined an internal class to implement the public interface.The internal class


only had a constructor.


class AA implements publicinterface


{


public AA()


{


}


}





2


Defined an object BB of the class AA.


AA BB = new AA();





3


To call the method at demanded position.


BB.methodname();





When I compiled source file ,JCreator reported error:


External class name.AA is not absract and does not override abstract method methodNameOfPublic in package.





Now I am confused by calling a method from public interface that belongs with a third-party SDK and all the necessary packages successfully imported in Java.

How to call a method in a public interface in Java?
1) If the third party SDK provides the interface and expects you to use it to call, and they are the ones providing the implementation, then you just call it on their interface type, e.g. they have methods somewhere that return an object that implements the interface you refer to.





2) If the third party SDK expects YOU to implement the interface, then you must write a class that implements the interface. Just declaring that your class "implements publicinterface" is not sufficient. Your class must supply the implementation of all interface methods, otherwise there are still undefined methods and your class will have to be declare "abstract" (that is what the compiler is trying to tel you).





Example:


public interface Logger{





public void log(String msg);





}





public class ConsoleLogger implements Logger {





//implementation of Logger.log()


public void log(String msg){


System.out.println(msg);


}





}
Reply:at the top write


public [your class reference] implements [interface reference]


No comments:

Post a Comment