Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Implementing Interfaces
Java Objects Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Objects Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java objects.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Java functions with "single inheritance", meaning that a subclass can only inherit from one superclass. The reserved word extends can only be used to extend from one class. However, Java has interfaces, a class that allows multiple inheritance. An interface is a set of requirements that a class must implement. An interface is a list of constants and method headers with no method bodies. All methods and constants must be implemented by the class. Let's see how an interface can be used.
InterfaceTestOne.java
package exlcode;
public interface InterfaceTestOne {
int exampleVariableOne = -5;
void print();
}
InterfaceTestThree.java
package exlcode;
public class InterfaceTestThree implements InterfaceTestOne, InterfaceTestTwo {
// implements the method print() from InterfaceTestOne
public void print() {
System.out.println(exampleVariableOne);
}
// implements the method printGreeting() from InterfaceTestOne
public void printGreeting() {
System.out.println(exampleVariableTwo);
}
}
package exlcode;
public class InterfacesExample {
public static void main(String[] args) {
InterfaceTestThree interfaceTestThree = new InterfaceTestThree();
interfaceTestThree.print();
interfaceTestThree.printGreeting();
}
}
The Java reserved word implements is used instead of extends for interfaces. You are able to implement multiple interfaces by separating them with a comma. The class that implements an interface inherits the methods and the instance variables of the interface. However, similar to abstract classes, the methods have to be declared inside the class with a proper method body. The variables implemented in the interface do not necessarily have to be used in the class. In addition, methods from the interface must be declared public. All variables in an interface are public, static, and final by default.