Java Interfaces
Interfaces
package main.java;
public interface MyInterface {
public void myMethod(); // The code for this function is not defined here
}
package main.java;
public class MyImplementation1 implements MyInterface {
public void myMethod () {
System.out.println( "My implementation of interface" );
}
}
package main.java;
public class MyImplementation2 implements MyInterface {
public void myMethod () {
System.out.println( "My alternative implementation of interface" );
}
}
- Applying an interface requires that a class has the named functions defined.
- It's similar to inheritance but you use the "implements keyword instead of "extends".
- This is useful if you want to make an array of different classes that share the function(s) specified in the interface.
- Multiple interfaces can be applied to a class (just add the other interfaces after "implements", separating each with a comma).
Grouping objects with a shared interface
package main.java;
public class MainClass {
public static void main (String [] args) {
// Create array of various types of objects that implement the same interface
MyInterface1 [] objs = new MyInterface1 [2];
objs[0] = new MyImplementation1 ();
objs[1] = new MyImplementation2 ();
// Then you can call the shared function on each of them
for (MyInterface item : myList) {
item.myMethod();
}
}
}
- This is useful if you have a variety of class types, but you need them all to answer to perform a certain action in their own way (such as 'display').
Challenge
Create two classes (Teacher and Student) that apply an interface requiring them to have a getId function. Then, define that function within each of the classes. Finally, create an array that contains objects of both class types (Teacher and Student).
Quiz
Completed