15. Interfaces and Internal Classes in Java

Java is an object-oriented programming language that offers several features for building robust and flexible software. Among these resources, interfaces and internal classes are fundamental for creating complex and well-structured systems. In this chapter, we'll dive into the world of interfaces and internal classes in Java, exploring how they can be used to improve the design of your software.

What are Interfaces?

In Java, an interface is a reference type, similar to a class, that can only contain constants, signature methods, default methods, static methods, and nested types. Interfaces cannot contain constructors or non-signature methods (that is, methods that contain a body).

Interfaces are used to define a contract that classes can implement. This means that a class that implements an interface must provide concrete implementations for all abstract methods declared in the interface. A class can implement multiple interfaces, separating responsibilities and facilitating code maintenance and extensibility.


public interface Vehicle {
    void startEngine();
    void stopEngine();
    double getFuelCapacity();
}

Once an interface is defined, one or more classes can implement it:


public class Car implements Vehicle {
    @Override
    public void startEngine() {
        // Car-specific implementation
    }

    @Override
    public void stopEngine() {
        // Car-specific implementation
    }

    @Override
    public double getFuelCapacity() {
        // Car-specific implementation
        return 50.0;
    }
}

Internal Classes

Internal classes, also known as nested classes, are classes defined within another class. They are useful when one class must be linked to another class, or when the design groups two classes that will only be used together.

There are four types of inner classes:

  • Regular Internal Class: It is a non-static class defined in the body of another class.
  • Static Internal Class: Also known as a static nested class, it is a static class defined in the body of another class.
  • Local Internal Class: It is a class defined within a block of code, such as a method.
  • Anonymous Internal Class: It is an unnamed class defined and instantiated in a single expression.

Inner classes can access members of the outer class, including private members. This allows for closer coupling between classes and can lead to a more cohesive design.


public class OuterClass {
    private String secret = "Time is an illusion.";

    class InnerClass {
        public void revealSecret() {
            System.out.println("The secret is: " + secret);
        }
    }
}

In the example above, InnerClass can access the private member secret of OuterClass.

Interfaces and Internal Classes in Action

Interfaces and internal classes offer many benefits when used correctly. For example, we can use interfaces to define a set of methods that multiple inner classes must implement, allowing the outer class to interact with its inner classes in a uniform way.


public class ActionExecutor {
    private interface Action {
        void execute();
    }

    class FirstAction implements Action {
        @Override
        public void execute() {
            // First action
        }
    }

    class SecondAction implements Action {
        @Override
        public void execute() {
            // Second action
        }
    }

    public void performActions() {
        new FirstAction().execute();
        new SecondAction().execute();
    }
}

In this example, the ActionExecutor class has two inner classes that implement the Action interface. The performActions method creates instances of both internal classes and performs their actions. This demonstrates a practical use of interfaces and internal classes to organize and perform a set of related actions.

Conclusion

Interfaces and internal classes are powerful tools in any Java programmer's arsenal. Interfaces allow you to define contracts that can be implemented by multiple classes, promoting code reuse and flexibility. Inner classes allow you to logically group classes that are only used together, which can simplify your code and increase readability.

When designing your software, consider where interfaces and internal classes can beapplied to improve the structure and clarity of your code. Understand the differences between the types of inner classes and when to use each. Remember that good object-oriented design is not just about utilizing advanced language features, but about creating code that is easy to understand, maintain, and expand.

With this knowledge, you are well equipped to advance your Java learning journey and develop software that is robust, efficient, and easy to work with.

Now answer the exercise about the content:

Which of the following statements best describes the use of interfaces in Java?

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

You missed! Try again.

Article image Enums and annotations

Next page of the Free Ebook:

101Enums and annotations

6 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