PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

Interface

p225 An interface is forcing the developer to implement methods, it is a contract. In an interface everything must be an abstract method.
 RunCode
/**
 * Every class that implements an interfece ...
 * must @Override all interface methods
 */

class LearningApp {
    public static void main(String[] args) {}
}

interface Canine { // no class keyword

    public abstract void play();
    public void sing(); // abstract by default
    //public void move() {}; // Error: Interface methods cannot have body
}

interface Feline {}

class Dog implements Canine {
    
    @Override public void play() {}
    @Override public void sing() {}
}
... 11 lines
˄˄˄
When you add methods to an interface, current related classes will break. You'll need to create more interfaces that extend initial interface.
 RunCode
/**
 * When you add methods to existing interfaces ...
 * you'll need to extend the interface ...
 * so that current objects won't break
 */
class App {
    public static void main(String[] args) {
        
        new Dog();
        new Bird();
    }
}

interface Animal {
    public void eat();
}

interface AnimalWithWings extends Animal {
    public void fly();
}

class Dog implements Animal {
    @Override public void eat() {}
}

class Bird implements AnimalWithWings {
    @Override public void eat() {}
    @Override public void fly() {}
}
... 18 lines
˄˄˄
Task

 CompleteTask
/** 
 * Define Dog class ... 
 * Dog class must implement the correct interface
 */

class LearningApp {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.bark(); // The dog is barking
    }
}

interface Canine {
    public abstract void bark();
}

interface Feline {
    public abstract void roar();
}

...

solution code
Questions    
14. Constructor
13 . Interface
Last update:   23-07-2021

        A B C D E F
🔔
1/3