Java Interfaces
Interfaces:
package main.java;
public interface MyInterface1 {
public int myMethod1(); // The code for this function is not defined here
}
package main.java;
public class MyClass implements MyInterface1 {
public int myMethod1 () {
System.out.println( "testing " + myMemberVar1 );
}
}
- 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)
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