user54089 user54089 - 7 months ago 8
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

.getValue()
method that returns a single
double
, or a
.getTimestamp()
method that returns a single
long
, etc.

Can this be done?

Answer

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();
    }
 }