user54089 user54089 - 5 months ago 6x
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?


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