Introduction to Object-Oriented Programming in Java
The ideas behind object-oriented programming in Java: classes and objects, encapsulation, an object's behavior, state and identity, finding classes from nouns and verbs, and the uses-a, has-a and is-a relationships between classes with UML notation.
kvi5hnuCode Sprout team member11 min readOn this page
You now know the fundamental building blocks of Java: types, operators, strings, control flow and arrays. With those alone you could write any program, at least in principle. But large programs written as one long list of procedures quickly become unmanageable. Java's answer, like most modern languages', is object-oriented programming (OOP).
This part of the course teaches you to use objects from the standard library and to design and write your own classes. If you haven't programmed in an object-oriented language before, read it carefully: OOP requires a different way of thinking from step-by-step procedural code, and that shift takes some practice. If you know C++ or C#, much will be familiar, but there are enough differences that the "for C++ programmers" notes are worth reading.
This first article is conceptual: what objects and classes are, and how to think about designing with them.
From Procedures to Objects
Traditional structured (procedural) programming, as developed in the 1970s, designs a program as a set of procedures (algorithms) and then decides how to store the data they manipulate. Niklaus Wirth, the designer of Pascal, named his famous book Algorithms + Data Structures = Programs. Algorithms came first.
OOP reverses the order: it puts the data first, and then designs the operations that work on that data. An object-oriented program is made of objects. Each object has some functionality exposed to its users and a hidden implementation. Many objects come off-the-shelf from libraries; others you design yourself. As long as an object does what its specification promises, you don't care how it does it.
For small problems, breaking the work into procedures is fine. For large ones, objects scale much better. Imagine a web browser that needs 2,000 procedures, all manipulating a shared pool of global data. In an object-oriented design, it might be 100 classes with about 20 methods each. That's much easier to understand, and much easier to debug. If some piece of data ends up in a bad state, you only need to search the 20 methods that have access to it, not 2,000 procedures.

Classes
A class describes how objects are made: what data they hold and what they can do. A common analogy: a class is a cookie cutter, and objects are the cookies. Creating an object from a class is called constructing it, and the object is an instance of the class.
You've already been writing classes: in Java, all code lives inside classes. The standard library supplies thousands of classes, for user interfaces, dates, networking, collections and much more. You'll still write your own classes to model the things your particular application deals with: customers, orders, invoices, game characters.
Encapsulation
Encapsulation (also called information hiding) is the central idea in working with objects. It means combining data and behaviour in one package and hiding the implementation details from the object's users.
- The data stored in an object is held in its instance fields.
- The procedures that operate on the data are its methods.
- The current values of an object's instance fields are its state. Calling a method may change the state.
The key rule: methods should never directly access the instance fields of objects of other classes. Programs interact with an object's data only through the object's methods. That gives objects their "black box" behaviour. The class can completely change how it stores its data (switch from separate year/month/day fields to a single day count, say), and as long as its methods behave the same, no other code knows or cares. That's the key to reuse and reliability.
Inheritance, in one paragraph
Classes can be built by extending other classes. The new class gets all the fields and methods of the class it extends, and adds its own. This is called inheritance. In fact, every Java class extends a "cosmic superclass" called Object. Inheritance gets its own part of the course, right after this one.
Objects: Behavior, State and Identity
To work with objects, you need to identify three key characteristics:
| Characteristic | Question it answers | Example (a library member) |
|---|---|---|
| Behavior | What can you do with the object? Which methods can you call? | borrow a book, return it, pay a fine |
| State | How does the object currently look? How does it react to method calls? | current loans, fines owed, card expiry date |
| Identity | How is this object distinguished from others with the same behavior and state? | member #2041 vs. member #2042 |
- All instances of a class share the same behavior: it's defined by the class's methods.
- Each object stores its own state, which may change over time, but not spontaneously: a change of state must be the result of method calls. If an object's state changes without a call on that object, someone broke encapsulation.
- State doesn't fully describe an object, because each object has its own identity. Two members who happen to hold the same loans are still two different members. Instances usually differ in state, and always differ in identity.
These characteristics affect each other. State can influence behavior: a member whose card has expired should refuse a request to borrow; a member with no loans has nothing to return.
Identifying Classes
In a procedural program, you start at the top, with main, and break it down. An object-oriented system has no "top", and newcomers often wonder where to begin. The answer: first identify the classes, then add methods to each one.
A simple rule of thumb: look for nouns in the description of the problem; they suggest classes. Verbs suggest methods.
Take a library lending system. Its description might mention these nouns:
- Book
- Member
- Loan
- Catalog
- Fine
Each one is a candidate class: Book, Member, Loan and so on. The verbs follow: members borrow and return books, loans get renewed, fines get paid. For every verb, ask which object is best placed to carry it out. Borrowing belongs to Member, because a member knows how many loans it already holds and what its limit is. So borrow becomes a method of Member that takes a Book.
Nouns and verbs are only a starting point. Experience teaches you which ones really matter. Two widely used checks:
- Single responsibility: each class should have one clear purpose that you can describe in a sentence. A class called
LibraryManagerHelperUtilusually signals a design that hasn't found its classes yet. - "Tell, don't ask": prefer telling an object to do something (
member.suspend()) over pulling out its data and doing the work elsewhere (if (member.getFinesOwed() > LIMIT) { member.setStatus(SUSPENDED); ... }).
Relationships Between Classes
The most common relationships between classes are:
| Relationship | Informal name | Meaning | Example |
|---|---|---|---|
| Dependence | "uses-a" | a class's methods use or manipulate objects of another class | Member uses Catalog to check that a book is available |
| Aggregation | "has-a" | objects of one class contain objects of another | a Member has Loans |
| Inheritance | "is-a" | a more special class extends a more general one | a StudentMember is a Member |
Dependence ("uses-a")
Dependence is the loosest relationship. Member depends on Catalog, because borrowing has to confirm that a copy is on the shelf. Loan has no reason to know about Catalog at all, so it doesn't depend on it.
Keep dependencies to a minimum. If class A doesn't know that class B exists, then changes to B can't break A. In software-engineering terms, you want low coupling between classes. Low coupling makes classes easier to understand, test and change independently.
Aggregation ("has-a")
Aggregation is the easiest to picture: a Member object holds Loan objects. Some modeling methodologies prefer the more general term association (and distinguish composition, where the parts' lifetime is bound to the whole). For programmers, "has-a" captures the essential idea: a field that refers to other objects.
Inheritance ("is-a")
Inheritance connects a specialised class to a general one. StudentMember extends Member: it applies a lower borrowing limit and waives some fines, while inheriting everything else, such as borrowing and returning books. If class D extends class C, then D inherits C's methods and adds capabilities.
UML class diagrams
Many developers draw class diagrams in UML (Unified Modeling Language) to show classes and their relationships. Classes are rectangles, and relationships are lines with specific arrowheads:

| Relationship | UML connector |
|---|---|
| Inheritance | solid line with a hollow triangle pointing to the superclass |
| Interface implementation | dashed line with a hollow triangle (interfaces come later) |
| Dependency | dashed line with an open arrowhead pointing to the class that is used |
| Aggregation | solid line with a hollow diamond at the containing class |
You don't need heavyweight UML tools. Whiteboard sketches, text-based tools such as PlantUML and Mermaid (which render diagrams from plain text and are supported in many wikis and on GitHub), and the class diagram view in IntelliJ IDEA's paid tier are common in practice.
Common questions
Is OOP still the main way to write Java? Yes, but modern Java mixes styles. You design with classes and interfaces, use records for plain data, sealed types and pattern matching for closed sets of alternatives, and lambdas and streams for data processing. Knowing when to use each style is part of being fluent in modern Java.
What is the difference between a class and an object?
A class is the definition: which fields objects have and which methods they offer. An object is one concrete instance, created at runtime with new, with its own field values. One class can have any number of objects, each with its own state and identity.
What does "encapsulation" mean in practice?
Make fields private, and expose only methods that keep the object in a valid state. Callers can't set an Account balance to a negative number directly. They have to call withdraw, which checks the rule. You can then change the internal representation without breaking any callers.
Should I prefer inheritance or composition? Prefer composition (has-a) unless there is a genuine "is-a" relationship and the subclass truly honours the superclass's contract. Composition couples classes more loosely and is easier to change. The inheritance part of the course discusses this in detail.
Do I need UML to design classes? No. Many teams never draw formal UML. Quick sketches, or text-based diagrams in Mermaid or PlantUML, are enough to discuss a design. What matters is thinking about responsibilities and dependencies before writing code.
Summary
- OOP organizes programs around objects, which combine data (instance fields) and behaviour (methods). It puts data first, unlike procedural programming.
- A class is a blueprint; objects are instances constructed from it.
- Encapsulation: hide the implementation and let other code access an object's data only through its methods. This allows reuse and safe change.
- Objects have behavior (methods), state (field values, changed only by method calls) and identity (distinct even if the state is equal).
- Find classes by looking for nouns and methods by looking for verbs. Give each responsibility to the object that knows the relevant data.
- Relationships: uses-a (dependence; keep coupling low), has-a (aggregation), is-a (inheritance). UML diagrams draw these with distinct connectors.
Practice Questions
What is encapsulation, and what benefit does it give when a class's internal data representation changes?
Encapsulation bundles data and methods in a class and hides the data, so other code can only use the object through its methods. If the class changes its internal representation but keeps its methods' behaviour, no other code needs to change.
Two Member objects hold exactly the same loans, fines and expiry date. Are they the same object? Which characteristic distinguishes them?
No. They're two distinct objects with equal state but different identity. In a library system, they'd be two separate members.
In a library system, "A member borrows a book; the librarian records the loan; overdue loans incur a fine." Suggest classes and methods.
Nouns suggest classes: Member, Book, Loan, Fine (perhaps Librarian, if staff actions need to be modeled). Verbs suggest methods: borrow/createLoan, isOverdue and computeFine on Loan, returnBook. A Loan naturally has-a Book and a Member.
Classify each relationship: (a) a Car has an Engine; (b) a SportsCar is a Car; (c) a Garage's repair method takes a Car parameter.
(a) aggregation ("has-a"); (b) inheritance ("is-a"); (c) dependence ("uses-a").
Why is low coupling desirable?
If a class depends on few other classes, changes to those classes are less likely to break it, and it's easier to understand, test and reuse in isolation.
Previous: Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
Next: Using Predefined Classes in Java: Objects, Object Variables and LocalDate
Related reading
- Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
- Java Arrays: Declaring, Initializing, for-each Loops and Copying
- Java Loops: while, do-while and for
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.