Java
Interfaces
Interfaces are essentially lighter, more restrictive abstract classes. They are to be implemented by other classes and used as blueprints, defining the structure to be inherited but not the way it should be filled out. (I believe, in theory, abstract classes can match the functionality of interfaces by simply restricting their functionality, but the restrictions are not enforced by the compiler in the case of the abstract class).
One primary difference between abstract classes and interfaces is that subclasses can implement multiple interfaces, whereas they can only have one superclass (thanks to the diamond problem). Additionally interfaces are not allowed to declare instance variables or refer to the state of the object, and are only allowed to define implementations via default methods (otherwise restricted to default methods), and so on.
Note that in other languages (i.e. C++, Python) interfaces are abstract classes; Java just uses a separate keyword for strict enforcing of a few flexibility differences.
Resources
Generics
Generics allow types or methods to operate on varying object types in a formalized, abstract manner. It provides an additional layer of abstraction over the typing system, allowing greater flexibility when the specific type is not known ahead of time.
Basic Generic Class
class Generic<T> {
// declare object of type T (e.g. String)
;
T object
// define constructor
Generic(T object) {
this.object = object;
}
// simple getter
public T getObject() {
return this.obj;
}
}
Here we can see that the simple Generic class is defined with some arbitrary type T
, that can be acted upon just like a fully specified type.
Basic Generic Function
// A generic method
static <T> void genericDisplay(T element) {
System.out.println(element.getClass().getName() + " = " + element);
}
Here is how a generic function may be implemented. Again using <>
notation, we can specify an arbitrary type T
in the function signature and parameter list. We act on this type in a general way, common to all expected classes; in this case, we simply print the element and its type name. using to_string
default methods (or something of the like) defined in all types that would be passed in.