ECS2301 Software Engineering and Project – Lesson 9 (Interface)

We learn about the importance of “Interface” feature of OOP:

In Java, an interface is a way to achieve abstraction. It’s like a blueprint of a class, defining a set of methods that any class implementing the interface must provide. Think of it as a contract that a class agrees to follow.

Interface declaration

An interface is declared using the interface keyword. It can have abstract methods (methods without a body) and constant variables.

/**
 * This only has the skeleton, you must implement the method in the target class
 * @author azmeer
 */
public interface Animal {
    void makeSound(); // Abstract method
    String getName(); // Another abstract method
}

Interface implementation

A class implements an interface using the implements keyword. The class must provide concrete implementations (with a body) for all methods declared in the interface.

/**
 *
 * @author azmeer
 */
public class Dog implements Animal{

    @Override
    public void makeSound() {
        System.out.println("Woof! Woof!");
    }

    @Override
    public String getName() {
        return "Dog";
    }
    
}

Another class using the ‘Animal’ interface.

/**
 * Must override the interface methods and implement here
 * @author azmeer
 */
public class Cat implements Animal {

    @Override
    public void makeSound() {
        System.out.println("Meow");
    }

    @Override
    public String getName() {
        return "Cat";
    }

}

Tester

/**
 * Make objects out of class for testing
 * @author azmeer
 */
public class W11aInterface1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Java Interface tester");

        Dog tommy = new Dog();
        tommy.makeSound();
        System.out.println(tommy.getName());
        
        Cat poosa = new Cat();
        poosa.makeSound();
        System.out.println(poosa.getName());

    }

}

All lessons >

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.