Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to declare that a variable implements an interface?

In Objective-C, I could do:

id<HTTPRequestDelegate> delegate;

to say that delegate (a variable of type id) conforms to the HTTPRequestDelegate protocol (or implements the HTTPRequestDelegate interface in Java speak).

That way, whenever I send a message defined by the HTTPRequestDelegate protocol to delegate, the compiler understands that delegate responds.

How do I do this, i.e., duck typing / dynamic typing, in Java?

like image 889
Jon Font Avatar asked Feb 04 '26 14:02

Jon Font


2 Answers

Duck typing doesn't exist in Java. If a class implements an interface, it must declare that this interface is implemented. It isn't sufficient just to have methods with the same signature as the ones in the interface.

An interface is a type, though, and you may declare a variable of this type. For example:

List<String> myList;

declares a variable myList of type List<String>, where List is an interface.

You may initialize this variable with any object implementing this List interface:

myList = new ArrayList<String>();

But then ArrayList must declare that it implements the List interface (which it does).

like image 148
JB Nizet Avatar answered Feb 06 '26 05:02

JB Nizet


//Static typing
HTTPRequestDelegate delegate;
like image 23
OscarRyz Avatar answered Feb 06 '26 05:02

OscarRyz