Skip to content

Comprehensive Object-Oriented Programming exercises demonstrating encapsulation, abstraction, inheritance, polymorphism, and composition in Java

Notifications You must be signed in to change notification settings

juan-cantero/oop-exercises-java

Repository files navigation

Object-Oriented Programming Exercises in Java

This project demonstrates fundamental Object-Oriented Programming (OOP) concepts through three practical activities implemented in Java.

Project Structure

objects/
├── app/
│   ├── src/main/java/org/example/
│   │   ├── Demo.java                    # ⭐ MAIN CLASS - Run this!
│   │   │
│   │   ├── UserProfile.java             # Activity 1: Encapsulation
│   │   ├── IProfileExporter.java
│   │   ├── JsonProfileExporter.java
│   │   ├── XmlProfileExporter.java
│   │   │
│   │   ├── Notification.java            # Activity 2: Inheritance & Polymorphism
│   │   ├── EmailNotification.java
│   │   ├── SmsNotification.java
│   │   ├── PushNotification.java
│   │   ├── NotificationService.java
│   │   │
│   │   ├── Character.java               # Activity 3: Composition over Inheritance
│   │   ├── IAttackBehavior.java
│   │   ├── IMovementBehavior.java
│   │   ├── SwordAttack.java
│   │   ├── MagicAttack.java
│   │   ├── WalkingMovement.java
│   │   └── FlyingMovement.java
│   │
│   └── build.gradle.kts
└── README.md

How to Run the Code

Prerequisites

  • Java 11 or higher
  • Gradle (or use the included Gradle wrapper)

Running the Demo

IMPORTANT: The main class is Demo.java located at app/src/main/java/org/example/Demo.java

Option 1: Using Gradle (Recommended)

cd objects/app
./gradlew run

Or on Windows:

cd objects\app
gradlew.bat run

Option 2: Using Gradle from project root

cd objects
./gradlew :app:run

Option 3: Compile and run manually

cd objects/app/src/main/java
javac org/example/*.java
java org.example.Demo

Option 4: Using an IDE

  1. Open the objects folder in your IDE (IntelliJ IDEA, Eclipse, VS Code)
  2. Navigate to app/src/main/java/org/example/Demo.java
  3. Right-click on the file and select "Run 'Demo.main()'"

What the Demo Shows

The Demo class (Demo.java) is the entry point that demonstrates all three activities:

Activity 1: Encapsulation and Abstraction

  • Creates a UserProfile with private fields and public getters/setters
  • Demonstrates email validation (must contain @)
  • Demonstrates password validation (minimum 8 characters)
  • Shows abstraction with JsonProfileExporter and XmlProfileExporter
  • Exports user profile in multiple formats without modifying the UserProfile class

Expected Output:

=== Activity 1: Encapsulation and Abstraction Demo ===

User profile created successfully!
Username: johndoe
Email: johndoe@example.com

--- Testing Email Validation ---
Error: Email must contain an @ symbol

--- Testing Password Validation ---
Error: Password must be at least 8 characters long

--- Exporting Profile (JSON Format) ---
{
  "username": "johndoe",
  "email": "johndoe@example.com"
}

--- Exporting Profile (XML Format) ---
<?xml version="1.0" encoding="UTF-8"?>
<UserProfile>
  <username>johndoe</username>
  <email>johndoe@example.com</email>
</UserProfile>

Activity 2: Inheritance and Polymorphism

  • Creates an abstract Notification base class
  • Implements concrete notification types: EmailNotification, SmsNotification, PushNotification
  • Uses NotificationService to send notifications polymorphically
  • Demonstrates the Open/Closed Principle - new notification types can be added without modifying the service

Expected Output:

=== Activity 2: Notification System Demo ===

Sending Email to john@example.com: Welcome to our service!
Sending SMS to +1234567890: Your verification code is 123456
Sending Push Notification to user123: You have a new message

Activity 3: Composition over Inheritance

  • Creates a flexible Character system using composition instead of inheritance
  • Uses behavior interfaces: IAttackBehavior and IMovementBehavior
  • Demonstrates mixing and matching behaviors: Flying Warrior, Walking Mage, etc.
  • Shows runtime behavior changes - a warrior can learn magic!

Expected Output:

=== Activity 3: Game Characters Demo ===

--- Flying Warrior ---
Aria is Attacking with a sword! Slash!
Aria is Flying through the air

--- Walking Mage ---
Gandor is Casting a powerful spell! Fireball!
Gandor is Walking on the ground

--- Spell Blade (Flying Mage) ---
Zephyr is Casting a powerful spell! Fireball!
Zephyr is Flying through the air

--- Dynamic Behavior Change ---
Aria learns magic and switches to magic attacks:
Aria is Casting a powerful spell! Fireball!

Key OOP Concepts Demonstrated

1. Encapsulation

  • Private fields with public getters/setters
  • Data validation in setters
  • Information hiding

Example: UserProfile class with private username, email, password

2. Abstraction

  • Interfaces define contracts (IProfileExporter, IAttackBehavior)
  • Hide implementation details
  • Separate "what" from "how"

Example: Different exporters implement the same interface

3. Inheritance

  • Abstract base classes define common behavior
  • Derived classes specialize behavior
  • Code reuse through class hierarchies

Example: EmailNotification extends Notification

4. Polymorphism

  • Treat different types uniformly
  • Runtime method dispatch
  • Write code that works with parent types

Example: NotificationService.sendBatch() works with any Notification type

5. Composition over Inheritance

  • Build complex objects from simple parts
  • More flexible than inheritance
  • Avoids "class explosion"

Example: Character composed of attack and movement behaviors

Project Configuration

The project uses Gradle as the build system. Key configuration in build.gradle.kts:

application {
    mainClass = "org.example.Demo"  // ⭐ Main class configuration
}

Troubleshooting

Issue: "Could not find or load main class Demo"

Solution: Make sure you're running from the correct directory and the main class is org.example.Demo

Issue: Gradle command not found

Solution: Use the Gradle wrapper: ./gradlew (Linux/Mac) or gradlew.bat (Windows)

Issue: Java version error

Solution: Make sure you have Java 11 or higher installed:

java -version

Learning Objectives

After running and studying this code, you should understand:

  1. ✅ How to achieve encapsulation with private fields and public methods
  2. ✅ How to implement abstraction using interfaces
  3. ✅ How inheritance creates class hierarchies
  4. ✅ How polymorphism enables flexible, extensible code
  5. ✅ Why composition is often better than inheritance
  6. ✅ How to apply the Single Responsibility Principle
  7. ✅ How to follow the Open/Closed Principle

Extending the Project

Try these exercises:

  1. Activity 1: Add a new CsvProfileExporter that exports profiles in CSV format
  2. Activity 2: Add a SlackNotification class without modifying NotificationService
  3. Activity 3: Create new behaviors like BowAttack or TeleportMovement

Related Projects

  • Go Implementation: See ../objects-go/ for the same exercises implemented in Go, with a comparison of how Go approaches OOP differently

License

This is an educational project for learning OOP concepts.

About

Comprehensive Object-Oriented Programming exercises demonstrating encapsulation, abstraction, inheritance, polymorphism, and composition in Java

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages