• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

interface as a function parameter?

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I really dint understand what's the use of sending an instance of a interface, as a function parameter? Cos you cant call the functions defined in the insterface...but hmm.. well if you have defined constances, I guess you can access them using interface instance as in (2)...
(1)
interface MyInterface
{
fun1();
fun2();
}
public class MyClass
{
MyClass(MyInterface interface) //what is the use of doing this?
{
}
}
(2)
interface MyInterface
{
int MAX_VALUE = 10;
int MIN_VALUE = 10;
}
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You aren't sending an instance of an interface as a method parameter. You are sending a reference type whose class implements the methods in the given interface. So, the benefit is that the method can accept an instance of any class, as long as the class of the instance implements the given interface.
You can call the methods, or query the variables (static and final implicitly) of the interface. Suppose we have the following simple interface
public interface ABC
{
public static final int x = 0;
public void doSomething() throws Exception;
}
Then provide an implementation of that interface:
public class X implements ABC
{
public void doSomething() throws Exception
{
// implementation of doing something here.
}
}
you could then have a method defined (somewhere) such as
public void execute(ABC abc)
{
// Leverage the interface, without having to know anything about
// the class which implements ABC.
abc.doSomething();
}
which can be called by:
X x = new X();
object.execute(x);
where object is an instance of the class that provides the execute() implementation.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic