Contract
Every class that implements an interfece must override all interface methods.
/**
* An interface is forcing the developer to implement methods ...
* it is like a contract.
*
* In an interface everything must be an abstract method.
*/
package com.minte9.oop.interfaces;
public class Contract {
public static void main(String[] args) {
Dog d = new Dog();
d.play();
// Dog is playing
}
}
class Dog implements Canine { // Look Here
@Override
public void play() {
System.out.println("Dog is playing");
}
@Override
public void eat() {
System.out.println("Dog is eating");
}
}
interface Canine {
// no class keyword
public abstract void play();
public void eat();
// abstract by default
// public void move() {};
// Error: Interface methods cannot have body
}
interface Feline {
public abstract void play();
}
Legacy
Extending interfaces is not recommended.
/**
* When you add methods to an interface, current related classes will break.
* You'll need to create more interfaces that extend initial interface.
*
* Where is possible, it is better to createa a new interface.
*/
package com.minte9.oop.interfaces;
public class Legacy {
public static void main(String[] args) {
new LA().setvalue(); // LA - setvalue
new LB().settype(); // LB - settype
}
}
class LA implements A {
@Override public void setvalue() {
System.out.println("LA - setvalue");
}
}
class LB implements B {
@Override public void setvalue() {
System.out.println("LB - setvalue");
}
@Override public void settype() {
System.out.println("LB - settype");
}
}
interface B extends A { // Look Here
public void settype();
}
interface A {
public void setvalue();
}
Default Method
Alternatively, you can define your new methods as default methods.
/**
* Default keyword allows you to add implementation in interfaces.
* Non default methods must be all define as abstract.
*/
package com.minte9.oop.interfaces;
public class DefaultMethod {
public static void main(String[] args) {
new AC().output(); // A - output
new BC().output(); // B - output
new AC().output_new(); // C - default output_new
new BC().output_new(); // C - default output_new
}
}
class AC implements C {
@Override public void output() {
System.out.println("A - output");
}
}
class BC implements C {
@Override public void output() {
System.out.println("B - output");
}
}
interface C {
void output();
default void output_new() { // Look Here
System.out.println("C - default output_new");
};
}
Last update: 450 days ago