OOP
Why Java needs an object model
Up to this point, a program could look like a set of variables, conditions, loops, and methods. OOP helps group these parts around the entities a program works with: users, orders, accounts, messages, and other domain objects. This makes code easier to divide by responsibility and evolve as a project grows.
In this section, we will gradually explore the main tools of Java's object model and see how they complement one another.
What this section includes
- Classes and objects. We will see how to describe custom types and create objects that a program can then work with.
- Constructors and fields. We will look at how an object's state is stored and how to provide its initial data when it is created.
- Encapsulation. We will learn to separate an object's internal implementation from the way the rest of the code should work with it.
- Inheritance. We will see how one type can extend another and when that relationship is actually useful.
- Polymorphism. We will explore how the same code can work with different implementations through a common type.
- Abstract classes and interfaces. We will learn ways to define shared capabilities and rules for a group of related types.
- The Object class. We will learn what all Java objects have in common and why this class appears throughout the standard API.
- Equals, hashCode, and toString. We will explore the main methods related to object comparison, hashing, and textual representation.
- Static and final. We will see how to express what belongs to the class as a whole, as well as what should not change.
- Nested classes. We will see how to keep closely related types together and control their scope more precisely.
- Enum. We will learn to represent a limited set of meaningful values as a separate type.
How the topics fit together
First, we will learn to describe individual objects and their state, then limit access to internal details and build relationships between types. After that, we will move on to shared contracts and behavior, and finally cover the basic features that make classes themselves easier to design.
OOP is not a set of rules for the sake of rules.
Its tools are meant to make object responsibilities and relationships easier to understand.
Next, we will study each tool separately and see when it actually makes code simpler.