Interfaces
-
What we’ll cover
What is an Interface?
Declaring an Interface
Implementing an Interface
Converting to an Interface Type
-
What we’ll cover (continued)
Casting and instanceof
Extending Interfaces
Constants
Static and Default Methods
-
Types (Classes & Interfaces)
-
Types
- Types are everywhere in computing
- Without them, bits are very hard interpret
int
andchar
-01000001
is itA
or65
??- And then
Object
and all of its subclasses (likeString
)
-
Classes
- Class acts as a factory of Objects
- Hierarchy of one superclass but 0..n subclasses
-
Types -> Interfaces
- Interface is another kind of Java type
- Interface like a contract
- Types (Classes and Interfaces) can implement many interfaces
-
Interfaces
- An interface is a
contract
that all classes implementing it must follow. - Code can be written against the interface without worrying about how an actual object will do it.
- Couples a class to a behavior
- Like a light class, a way to partition/divide/organize behavior
-
Comparable Interface
- Consider the
Comparable
interface.
public interface Comparable<T> {
public int compareTo(T o);
}
public class Something implements Comparable<Something> {
public int someInt;
public Something(int someInt) {
this.someInt = someInt;
}
public int compareTo(Something other) {
return this.someInt - other.someInt;
}
}
-
Interface Comparable<T>
- Java Comparable interface is used to order the objects of a user-defined class.
- This interface is found in the java.lang package and contains only one method
compareTo(Object)
. -
It provides single sorting sequence only
- Classes provided will most often provide you compareTo method to allow them to be sorted, such as Class String
public int compareTo(String anotherString)
-
Interface Comparable<T>
- For classes we create, to give users the ability to sort them, we need to have our class implement **Comparable
** - Sorting methods need to know how to rank any two objects
- Once we know how to compare any Two objects, we can build an algorithm to sort them
public static void main(String[] args){
Sayian[] sayians = new Sayian[3];
sayians[0] = new Saiyan("Vegeta", 5000);
sayians[1] = new Saiyan("Goku", 9000);
sayians[2] = new Saiyan("Gohan", 3000);
Arrays.sort(sayians);
for (Sayian s: sayians)
System.out.println("Name=" + s.getName()
+ ", order=" + s.getPowerLevel());
}
-
Interface Comparable<T>**
- There is no way for this method to know how to sort these objects
- Implementing Comparable tells the sort method that these objects can respond to the comparetTo(T t) request.
public class Saiyan implements Comparable<Saiyan>
{
...
public int compareTo(Saiyan other){
return Integer.compare(powerLevel, other.powerLevel )
}
...
}
- -
Declaring an interface
- To create an interface, use the keyword
interface
. - The interface should contain only method declarations.
- All methods of an interface are implicitly public.
public interface SomeInterface {
boolean someBoolFunc();
Object funcReturnsAnObject();
ReturnType functionName();
}
-
Declaring an interface: example
You can use the interface as a designation when a type is needed. Any type of object, as long as it adheres to the interface’s contract, can be used.
public static void someFunction(SomeInterface something) {
if(something.someBoolFunc()) {
Object o = something.funcReturnsAnObject();
// do something with o
}
}
-
Implementing an interface
- The
implements
keyword is used to declare that a class is using an interface
-
public interface SomeInterface {
boolean someBoolFunc();
Object funcReturnsAnObject();
ReturnType functionName();
}
public class SomeClass implements SomeInterface {
public SomeClass() { }
public boolean someBoolFunc() { return true; }
public Object funcReturnsAnObject() { return new Object(); }
public ReturnType functionName() {
// Must return some ReturnType
}
}
-
Properties of Interface
- Interfaces are not classes, you can never instantiate an interface.
- You can declare a reference variable of type interface.
- As long as the class implements the interface, you can assign it to that reference variable.
-
If you have this Interface…
package io.zipcoder.Marvel
public interface GuardianOfGalaxy {
Double attackEnemy(Enemy enemy);
String battleCry();
}
-
Then you can create a class that implements that interface…
package io.zipcoder.Marvel
public Groot implements GuardianOfGalaxy {
public Double attackEnemy(Enemy enemy){
...
}
public String battleCry() {
return "I am Grooooot!";
}
}
-
- You can create a reference and assign it the type of an interface, you DON’T instantiate interfaces.
- You can, however, make that reference variable to any object that implements that interface.
- This is a live example of polymorphism.
package io.zipcoder.Marvel
public class Guardians {
public assembleGuardians(){
GuardianOfGalaxy rocket = new GuardianOfGalaxy(); // ERROR
GuardianOfGalaxy groot = new Groot(); // Works Great
}
}
- -
Interface and Abstract Classes
- A class can only extend a single class
- But there will be times when you would like to apply multiple inheritance to a class.
- This can be accomplished via implements.
- Interfaces are polymorphic
-
public abstract GuardianOfGalaxy {
abstract Double attackEnemy(Enemy enemy);
abstract String battleCry();
}
public abstract Avengers {
abstact void AvengersAssemble();
}
-
// an object can only extend one type
public class IronMan extends Avengers , GuardianOfGalaxy{ // Error
....
}
-
A Class extends Once, implements Many.
- In Java, a class can only extend from one other class
- This keeps things simpler
- However, classes can implement as many interfaces as they would like.
-
public interface GuardianOfGalaxy {
Double attackEnemy(Enemy enemy);
String battleCry();
}
public interface Avengers {
void AvengersAssemble();
}
public class IronMan implements Avengers, GuardianOfGalaxy{...}
-
-
Converting to an Interface Type
List
someList = new ArrayList<>();
List
is the supertype of ArrayList
ArrayList
is the subtype of List
This lets us swap out code implementations easily.
-
Casting and instanceof
You can cast a supertype to a subtype if you are certain that the object really is of that subtype.
If it isn’t the right type, you’ll get a compile-time error or a class cast exception.
We can, however, write some code to make sure that the cast will be okay using instanceof
-
public interface SomeInterface { boolean someBoolFunc(); }
public class Implementer implements SomeInterface {
public Implementer() { }
public boolean someBoolFunc() { return true; }
public void someOtherFunc() {
System.out.println("Some Other Function");
}
}
public void demo() {
SomeInterface something = // something;
if(something instanceof Implementer) {
Implementer letsUseIt = (Implementer) something;
something.someOtherFunc();
} else {
// not an instance of Implementer
}
}
-
Extending Interfaces
You can extend interfaces. This means that you can have interfaces using other interfaces.
Any class implementing an extended interface must implement all of the methods from ALL of the interfaces.
-
public interface SomeInterface {
boolean someBoolFunc();
}
public interface ExtendoInterface extends SomeInterface{
int someIntFunc();
}
public class Usage implements ExtendoInterface {
public Usage() {}
public int someIntFunc() { return 42; }
public boolean someBoolFunc() {return true; }
}
-
Implementing Multiple Interfaces
public class Something implements
AnInterface,
AnotherInterface,
ThirdInterface {}
-
Constants
All variables in an interface become public static final
.
-
Static and Default Methods
-
Collection
vsCollections
- Allows for interface evolution
- This means that when new things are added, by adding a default method the older code will still work fine.
-
public interface Example {
default boolean isTrue() {
return true;
}
public static boolean isEven(int n) {
return n % 2 == 0;
}
}
-
Resolving Default Method Conflicts
public interface FirstExample {
default boolean isTrue() { return true; }
}
public interface SecondExample {
default boolean isTrue() { return false; }
}
public class Example implements FirstExample, SecondExample {
// must have
public boolean isTrue() { return true; }
}
error: class Example inherits unrelated defaults for isTrue() from types FirstExample and SecondExample
-
Examples
public class Something implements Comparable<Something> {
public int someInt;
public Something(int someInt) {
this.someInt = someInt;
}
public int compareTo(Something other) {
return this.someInt - other.someInt;
}
}
-
Notable/useful interfaces
- Comparator
- Runnable
- EventHandler
- Serializable
- Cloneable