Learn Java Tutorial for Beginners (Video), Part 23: Interfaces

A tutorial on interfaces in Java. Discover how you can use interfaces almost everywhere where you'd normally use classes, with one important exception. Interfaces have a variety of uses, including helping to specify functionality, helping to separate one class from another, summarising functionality among similar classes and implementing the Java version of a "callback". Although I don't cover all possible uses here, in this video I show you almost all of the mechanics of creating and using interfaces.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

App.java:

 

public class App {
    
    public static void main(String[] args) {
        
        Machine mach1 = new Machine();
        mach1.start();
        
        Person person1 = new Person("Bob");
        person1.greet();
        
        Info info1 = new Machine();
        info1.showInfo();
        
        Info info2 = person1;
        info2.showInfo();
        
        System.out.println();
        
        outputInfo(mach1);
        outputInfo(person1);
    }
    
    private static void outputInfo(Info info) {
        info.showInfo();
    }

}

 

Machine.java:

 

public class Machine implements Info {
    
    private int id = 7;
    
    public void start() {
        System.out.println("Machine started.");
    }

    public void showInfo() {
        System.out.println("Machine ID is: " + id);
    }
}

 

Person.java:

 

public class Person implements Info {
    
    private String name;
    
    public Person(String name) {
        this.name = name;
    }

    public void greet() {
        System.out.println("Hello there.");
    }

    @Override
    public void showInfo() {
        System.out.println("Person name is: " + name);
    }
}

 

Info.java:

 

public interface Info {
    public void showInfo();
}

 

IStartable.java:

 

public interface IStartable {
    public void start();
    public void stop();
}
 
Machine started.
Hello there.
Machine ID is: 7
Person name is: Bob

Machine ID is: 7
Person name is: Bob