user54089 user54089 - 2 years ago 57
Java Question

Enforcing that an object has specific kinds of methods?

I am making a new class that accepts a list of objects as an argument.

However I want to make it so these objects can be anything as long as they have certain methods, for example a

method that returns a single
, or a
method that returns a single
, etc.

Can this be done?

Answer Source

You can use an interface or implementation inheritance,

 interface Foo{
   long getTimestamp();

 class Bar implements Foo{
   ... impl ..

And then your methods will take a List of subtypes of Foo ( the super type)

 void fn(List<? extends Foo> foos){
    for(Foo foo:foos){
      long time = foo.getTimestamp();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download