Interfaces
Interfaces
public void eats() { this is OK, because the return types match (covariant or same)
System.out.println("Dog is eating.");
}
// duplicate methods, example #2
}
Default Interface Methods
• imagine you have an interface which is implemented by 100 classes
• for some reason you need to add a another method in your interface
• if this method were abstract, you would need to implement it in all 100 classes
• this is solved by making a method default (non-abstract)
• default method must have a body (default implementation)
public interface Mammal {
public void walks();
public void eats();
default void sleeps() { no need to implement sleeps() in classes which implement Mammal
System.out.println("A mammal sleeps.");
}
}
public class Dog implements Mammal {
public void walks() { System.out.println("Dog walks."); }
public void eats() { System.out.println("Dog eats."); }
}
public class Cat implements Mammal {
public void walks() { System.out.println("Cat walks."); }
public void eats() { System.out.println("Cat eats."); }
}
Rules for Using Default Methods
1. Keyword default with a method can only be used in the interface
3. Implicitly public
6. If the class inherits two or more default methods with the same method
signature, then it must override the method
public interface Car {
public default int getMaxSpeed() { return 100; }
}
public interface Truck {
default int getMaxSpeed() { return 70; }
}
public class Van implements Car, Truck {
public int getMaxSpeed() { we must override getMaxSpeed()
return 80; because there are two of them with a same signature
}
public int getMaxSpeedCar() {
return Car.super.getMaxSpeed(); this is how we call the default method
} from Car interface
}
// static interface methods
}
static methods cannot be overriden!
return Car.getMaxSpeed();
}
// private interface methods
int speed = 70 * 2;
return speed;
return calculateSpeed();
}
Rules for Using Private Interface Methods
1. marked with keyword private
int getMaxSpeed();
int getHorsePower();