11.8. Structure of Classes and Objects in Java: Interfaces

In Java, object-oriented programming is a fundamental paradigm, and understanding classes and objects is essential for any developer. A class is a structure that defines the state and behavior of an object, while an object is an instance of a class. Within this context, interfaces play a crucial role by defining a contract that classes can implement, thus allowing a high level of abstraction and flexibility in software design.

What are Interfaces in Java?

An interface in Java is a reference type, similar to a class, which can contain constants, abstract methods, default methods, static methods and private methods. It is a mechanism that allows full abstraction, providing a set of methods that a class must implement, without providing an implementation. Interfaces are declared using the interface keyword, and a class that implements an interface must provide concrete implementations for all of its abstract methods.


public interface Vehicle {
    void start();
    void stop();
    double getFuelCapacity();
}

Implementing Interfaces

When a class implements an interface, it must provide implementations for all abstract methods declared in the interface. The implements keyword is used in the class declaration to specify that the class is implementing an interface.


public class Car implements Vehicle {
    private double fuelCapacity;

    public Car(double fuelCapacity) {
        this.fuelCapacity = fuelCapacity;
    }

    @Override
    public void start() {
        System.out.println("Car started.");
    }

    @Override
    public void stop() {
        System.out.println("Car stopped.");
    }

    @Override
    public double getFuelCapacity() {
        return fuelCapacity;
    }
}

A class can implement multiple interfaces by separating them with a comma, which is Java's way of supporting multiple type inheritance.

Advantages of Using Interfaces

Interfaces are powerful software design tools for several reasons:

  • Abstraction: Interfaces allow you to define a contract that specifies what a class should do, without worrying about the how. This promotes cleaner, more modular software design.
  • Decoupling: Because interfaces are abstractions, they help decouple the code, making it easier to maintain and scale.
  • Polymorphism: Interfaces are a means of achieving polymorphism in Java, allowing objects of different classes to be treated uniformly.
  • Flexibility: Interfaces allow you to change the implementation of a class without changing the code that uses the interface, which is a significant advantage for long-term code maintenance.

Default Methods and Static Methods

Java 8 introduced default methods and static methods in interfaces. Default methods have a default implementation and are not required to be overwritten by classes that implement the interface. This allows new methods to be added to existing interfaces without breaking the classes that implement them.


public interface Vehicle {
    void start();
    void stop();
    double getFuelCapacity();

    default void turnAlarmOn() {
        System.out.println("Turning the vehicle alarm on.");
    }

    default void turnAlarmOff() {
        System.out.println("Turning the vehicle alarm off.");
    }
}

Static methods, on the other hand, are methods that belong to the interface and not to the instance of a class that implements it. They can be called directly from the interface.


public interface Vehicle {
    static String getVehicleType() {
        return "Unknown";
    }
}

Functional Interfaces and Lambda Expressions

Java 8 also introduced the concept of functional interfaces, which are interfaces that contain only a single abstract method. They are used as the basis for lambda expressions and method references, allowing a succinct and functional syntax for passing behavior as an argument.


@FunctionalInterface
public interface SimpleFunction {
    void execute();
}

// Using a lambda expression
SimpleFunction function = () -> System.out.println("Hello, World!");
function.execute();

Considerations When Using Interfaces

When designing your software, it is important to consider when and how to use interfaces. They are most useful when you have multiple classes that must follow the same contract, or when you want to define a role that can be played by objects of different classes. At theHowever, interfaces should not be used indiscriminately. If an interface isn't adding value to your software design, rethink its use.

In summary, interfaces in Java are a powerful tool that brings flexibility, abstraction, and polymorphism to object-oriented software design. They enable developers to create systems that are easy to maintain and extend, promoting robust and scalable coding practices.

Now answer the exercise about the content:

_Which of the following statements is true about interfaces in Java?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Structure of classes and objects in Java: Abstract Classes

Next page of the Free Ebook:

67Structure of classes and objects in Java: Abstract Classes

4 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text