DEV Community

Yoshi
Yoshi

Posted on • Edited on

Discovering the Purpose of Interfaces as a Beginner🌱

While studying Java, I encountered the concept of interfaces. However, when I searched online or asked AI, most information focused on implementation details and usage tips, not on the core purpose of interfaces. As a Java beginner, I found that understanding interfaces in relation to classes helped clarify their purpose, so I’d like to share those insights here.

The Role of Classes and Interfaces

First, a class manages an object’s attributes (variables) and behaviors (methods) as a whole, representing specific concepts or things. For example, in sports, classes like Baseball, Bowling, and JavelinThrow each have unique attributes and methods. These can be summarized in a table:

Name Attribute Method
Baseball pitcher throw
Bowling player throw
JavelinThrow thrower throw

An interface is used to provide a common “behavior” (method) across different classes. For example, if the throw action is required in multiple classes, it can be defined as a Throwable interface and implemented in each class. This way, the “throw” action is consistently provided, while each class can customize its specific details (such as the speed of a pitch in baseball, the weight of the ball in bowling, or the angle in javelin throwing).

With this understanding, in the context of the table shown earlier, classes can be thought of as managing things horizontally, while interfaces add functionality vertically. Since classes can implement multiple interfaces, this setup allows each class to adopt various behaviors as needed.

Name Attribute Method1 Method2
Baseball pitcher throw isSuccess
Bowling player throw isSuccess
JavelinThrow thrower throw isSuccess

Naturally, each class can also add unique methods.

Name Attribute Method1 Method2 Method3
Baseball pitcher throw isSuccess getPitchCount
Bowling player throw isSuccess isSecondThrow
JavelinThrow thrower throw isSuccess checkWindConditions

Differences from Abstract Classes

This perspective also makes it easier to distinguish interfaces from abstract classes. Both allow us to define a structure without implementation details, but interfaces are used for behaviors across multiple classes, whereas abstract classes manage shared attributes and basic methods.

Differences from Abstract Classes

Benefits of Interfaces

When an interface is implemented as class ClassName implements InterfaceName {}, it ensures that required methods are defined, creating consistency across different classes. Though I haven’t built complex Java programs yet, understanding that an interface acts as a “definition” for shared methods helps illustrate its value.

Top comments (0)