Java Interfaces
An interface is a contract: it lists the methods that a class promises to have. Classes implement the interface. A class can implement many interfaces, so it solves the “only one parent” limit of inheritance.
Define and implement
interface Payment {
void pay(double amount); // public and abstract by default
}
class CreditCard implements Payment {
public void pay(double amount) {
System.out.println("Paid " + amount + " by credit card");
}
}
class Upi implements Payment {
public void pay(double amount) {
System.out.println("Paid " + amount + " by UPI");
}
}
public class Main {
static void checkout(Payment method, double total) {
method.pay(total);
}
public static void main(String[] args) {
checkout(new CreditCard(), 1500);
checkout(new Upi(), 250.5);
}
}
Paid 1500.0 by credit card
Paid 250.5 by UPI
The checkout method works with any payment type, now and in the future. This is the power of programming to an interface.
Many interfaces
interface Flyer {
void fly();
}
interface Swimmer {
void swim();
}
class Duck implements Flyer, Swimmer {
public void fly() { System.out.println("Duck flies"); }
public void swim() { System.out.println("Duck swims"); }
}
public class Many {
public static void main(String[] args) {
Duck d = new Duck();
d.fly();
d.swim();
Flyer f = d; // the same object, seen as a Flyer
f.fly();
}
}
Duck flies
Duck swims
Duck flies
default and static methods
Since Java 8 an interface can have methods with a body. A default method is a ready made method which the class can use or override. A static method belongs to the interface.
interface Greeter {
String name();
default String greet() { // ready made
return "Hello, " + name() + "!";
}
static Greeter of(String n) { // static helper
return () -> n;
}
}
public class Default {
public static void main(String[] args) {
Greeter g = Greeter.of("Riya");
System.out.println(g.greet());
}
}
Hello, Riya!
Rules
- Interface fields are always
public static final(constants). - Methods are
publicby default, and you must write them aspublicin the class. - An interface can extend other interfaces.
- You can not create an object of an interface, but you can use it as a type.
Functional interface
An interface with exactly one abstract method is a functional interface. You can write it with a lambda. Java has many ready ones, like Runnable, Comparator and Function. See Java Lambda Expressions.
@FunctionalInterface
interface Calculator {
int apply(int a, int b);
}
public class Func {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
Calculator mul = (a, b) -> a * b;
System.out.println(add.apply(4, 5));
System.out.println(mul.apply(4, 5));
}
}
9
20
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |