A comprehensive educational project demonstrating Object-Oriented Programming (OOP) concepts using fruits as an intuitive analogy. This project is designed for newcomers to Java and OOP, featuring extensive comments, complete test coverage, and practical examples.
By studying this project, you will understand:
- The Four Pillars of OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction
- Java Programming Fundamentals: Classes, objects, interfaces, and method overriding
- Software Testing: Unit testing, integration testing, and test-driven development
- Code Organization: Clean code practices, documentation, and project structure
- Quick Start
- Project Structure
- OOP Concepts Demonstrated
- Core Classes
- Testing
- Installation & Development Environment
- Developer Experience (DX)
- Usage Examples
- Learning Path
- Contributing
- License
# Clone or download the project
cd Fruit
# Compile all Java files
javac *.java
# Run the main demonstration
java FruitDemo
# Run the comprehensive test suite
java FruitTestsFruit/
βββ README.md # This comprehensive guide
βββ CLAUDE.md # Development guidance for AI assistants
βββ Fruit.java # Main source file with all classes
βββ FruitTests.java # Comprehensive test suite (136 tests)
βββ TestFramework.java # Custom testing framework
βββ *.class # Compiled Java bytecode files
| File | Purpose | Lines of Code |
|---|---|---|
Fruit.java |
Main source with all OOP examples | ~550 |
FruitTests.java |
Complete test coverage | ~400 |
TestFramework.java |
Simple testing framework | ~115 |
Makefile |
Task automation and workflows | ~200 |
scripts/*.sh |
Enhanced development scripts | ~600 |
| Total Project | All files (code + config + docs) | ~3,300 |
- Private fields with controlled access
- Getter/setter methods for data protection
- Defensive copying in collections
private String name; // Hidden from outside access
private double weight; // Controlled through setters
public String getName() { // Controlled read access
return name;
}
public void setWeight(double weight) { // Controlled write access
this.weight = weight;
}- Abstract base class (
Fruit) defining common behavior - Concrete subclasses (
Apple,Orange,Banana) with specific implementations - Constructor chaining with
super() - Method inheritance and access to parent functionality
abstract class Fruit implements Edible {
protected String origin; // Accessible to subclasses
public abstract String getTaste(); // Must be implemented
}
class Apple extends Fruit {
public Apple(String variety, String color, double weight, String origin) {
super("Apple", color, weight, origin); // Call parent constructor
}
}- Method overriding for different behaviors
- Interface implementation across multiple classes
- Runtime type resolution with
instanceof - Collections of different types treated uniformly
// Same method call, different behaviors
Fruit[] fruits = {new Apple(...), new Orange(...), new Banana(...)};
for (Fruit fruit : fruits) {
fruit.eat(); // Each fruit eats differently!
}- Abstract classes that cannot be instantiated
- Interfaces defining contracts
- Hidden implementation details with public APIs
interface Edible {
void eat(); // What to do, not how
boolean isRipe(); // Contract definition
}
// Multiple classes implement the same interface differently
class Apple implements Edible { /* specific implementation */ }
class Orange implements Edible { /* different implementation */ }Edible: Defines eating behavior and ripeness checkingProcessable: Defines food processing capabilities
Fruit: Common properties and behaviors for all fruits- Encapsulated fields: name, color, weight, ripeness, origin
- Abstract methods:
getTaste(),getSeedCount() - Concrete methods:
eat(),ripen(),toString()
- Variety-based behavior: Different tastes based on apple variety
- Implements
Processable: Can be made into juice, pie, sauce - Demonstrates: Multiple interface implementation
- Seed variation: Seedless vs seeded oranges
- Method overriding: Custom
eat()method with peeling instruction - Demonstrates: Conditional logic and method customization
- Complex state management: 6-level ripeness system
- Unique behavior:
ageOneDay()method for time simulation - Advanced overriding: Custom
ripen()andisRipe()methods - Demonstrates: State-dependent behavior and complex inheritance
FruitBasket: Manages collections of fruits- Demonstrates "HAS-A" relationships
- Polymorphic operations on mixed fruit types
- Defensive copying for encapsulation
FruitDemo: Interactive demonstration of all OOP concepts- Object creation and manipulation
- Polymorphic method calls
- Interface usage and type checking
This project features 100% test coverage with 136 comprehensive tests.
| Test Suite | Tests | Purpose |
|---|---|---|
| Apple Tests | 14 | Core Apple functionality |
| Orange Tests | 14 | Core Orange functionality |
| Banana Tests | 21 | Complex Banana state management |
| FruitBasket Tests | 14 | Collection operations |
| Polymorphism Tests | 7 | Interface and inheritance behavior |
| Interface Tests | 8 | Contract compliance |
| Setter Method Tests | 7 | Encapsulation verification |
| ToString Method Tests | 9 | String representation |
| FruitBasket Output Tests | 4 | Output method behavior |
| Orange Eat Override Tests | 3 | Method overriding |
| Edge Case Tests | 8 | Boundary conditions |
| State Transition Tests | 27 | Complex state changes |
The project includes a simple but effective testing framework:
// Example test usage
TestFramework.assertEquals("Apple", apple.getName(), "Name should be set correctly");
TestFramework.assertTrue(apple.isRipe(), "Apple should be ripe after ripening");
TestFramework.assertFalse(banana instanceof Processable, "Banana should not be processable");# Run all tests with detailed output
java FruitTests
# Expected output: 136/136 tests passing (100% success rate)- Java Development Kit (JDK) 11 or higher
- Optional: Docker, Make, Git
- IDE Support: VS Code, IntelliJ IDEA, Eclipse
# Clone the repository
git clone <repository-url>
cd Fruit
# One-command setup and verification
make setup && make dev# Build and run in isolated environment
docker build -t java-oop-fruit .
docker run --rm java-oop-fruit
# Or use Docker Compose for full development stack
docker-compose up java-dev
docker-compose exec java-dev bash# Traditional approach
javac *.java
java FruitDemo
java FruitTestsmake help # Show all available commands
make dev # Full development cycle (clean, compile, test)
make quick # Quick compile and run (skip tests)
make test # Run comprehensive test suite
make clean # Clean compiled files
make docker-dev # Docker-based development
make watch # Auto-recompile on file changes
make stats # Show project statistics# Enhanced compilation with error handling
./scripts/compile.sh -v -c # Verbose compilation with cleanup
# Comprehensive testing with reporting
./scripts/test.sh -v -r # Verbose tests with report generation
# Advanced cleanup options
./scripts/clean.sh -d -i # Deep clean with interactive prompts# Start development environment
docker-compose up -d java-dev
# Run tests in isolated environment
docker-compose run test-runner
# Code quality analysis
docker-compose run code-quality
# File watching for auto-recompilation
docker-compose --profile watch up file-watcherThis project includes comprehensive developer tooling for a professional development experience.
- Auto-setup: Open folder in VS Code, install recommended extensions
- Tasks: Predefined build/test/run tasks (Ctrl+Shift+P β "Tasks: Run Task")
- Debugging: F5 to debug FruitDemo or FruitTests
- Settings: Consistent formatting, Java language support
- Import: Open folder as existing project
- Run Configurations: Pre-configured for FruitDemo and FruitTests
- Project Structure: Proper module setup and dependencies
- Automatic formatting across all editors
- Consistent indentation (4 spaces for Java)
- Line ending normalization (LF)
- Character encoding (UTF-8)
- Comprehensive .gitignore for Java, IDE, and OS files
- GitHub Actions CI/CD with multiple Java versions (11, 17, 21)
- Automated code quality checks and security scanning
# Development container with full toolchain
docker build --target builder -t java-oop-fruit:dev .
# Production container with minimal runtime
docker build --target runtime -t java-oop-fruit:prod .| Service | Purpose | Command |
|---|---|---|
java-dev |
Development environment | docker-compose up java-dev |
test-runner |
Automated testing | docker-compose run test-runner |
code-quality |
Static analysis | docker-compose run code-quality |
file-watcher |
Auto-recompilation | docker-compose --profile watch up |
- Multi-version testing (Java 11, 17, 21)
- Docker build verification
- Code quality analysis
- Educational content validation
- Security scanning with Trivy
# Run the same checks as CI
make ci # Compile and test
./scripts/test.sh -v -r # Comprehensive testing
docker-compose run code-quality # Quality analysis./scripts/compile.sh -v -c # Verbose output, clean first
./scripts/compile.sh --help # Show all options./scripts/test.sh -v -r -t 60 # Verbose, generate report, 60s timeout
./scripts/test.sh --no-compile # Test without recompiling./scripts/clean.sh -d # Deep clean (logs, cache, Docker)
./scripts/clean.sh -n # Dry run (show what would be cleaned)
./scripts/clean.sh -i # Interactive cleanupFruit/
βββ π .github/workflows/ # CI/CD automation
βββ π .idea/ # IntelliJ IDEA configuration
βββ π .vscode/ # VS Code workspace settings
βββ π scripts/ # Enhanced development scripts
βββ π .editorconfig # Code formatting rules
βββ π .gitignore # Git ignore patterns
βββ π Dockerfile # Multi-stage container build
βββ π docker-compose.yml # Development services
βββ π Makefile # Task automation
βββ π README.md # This documentation
- Incremental compilation with dependency tracking
- Docker layer caching for faster rebuilds
- Parallel test execution where possible
# Recommended daily workflow
make dev # Clean, compile, and test everything
make watch # Auto-recompile during development
make quick # Fast compile and run for demos
make docker-dev # Full containerized testing// Creating different types of fruits
Apple apple = new Apple("Granny Smith", "green", 150.0, "Washington");
Orange orange = new Orange("orange", 200.0, "Florida", true); // has seeds
Banana banana = new Banana(120.0, "Ecuador");
// Demonstrating polymorphism
Fruit[] fruits = {apple, orange, banana};
for (Fruit fruit : fruits) {
System.out.println(fruit.getName() + " tastes " + fruit.getTaste());
}// Working with interfaces
List<Processable> processableFruits = new ArrayList<>();
if (apple instanceof Processable) {
processableFruits.add(apple); // Apples can be processed
}
if (orange instanceof Processable) {
processableFruits.add(orange); // Oranges can be processed
}
// Note: Bananas don't implement Processable
for (Processable fruit : processableFruits) {
System.out.println("Can make: " + fruit.process());
}// Using composition with FruitBasket
FruitBasket basket = new FruitBasket("Alice");
basket.addFruit(apple);
basket.addFruit(orange);
basket.addFruit(banana);
basket.displayFruits(); // Show all fruits
basket.ripenAllFruits(); // Make all fruits ripe
basket.eatAllRipeFruits(); // Eat the ripe ones// Demonstrating complex state with Banana
Banana banana = new Banana(100.0, "Ecuador");
System.out.println("Day 0: " + banana.getTaste()); // "starchy"
banana.ageOneDay(); // Day 1
banana.ageOneDay(); // Day 2
System.out.println("Day 2: " + banana.getTaste()); // "sweet and creamy"
System.out.println("Ripe? " + banana.isRipe()); // true
// Continue aging...
for (int i = 0; i < 4; i++) {
banana.ageOneDay();
}
System.out.println("Day 6: " + banana.getTaste()); // "very sweet but mushy"
System.out.println("Ripe? " + banana.isRipe()); // false (overripe)- Start with
FruitDemo.java- Run it and observe the output - Read the comments in
Fruit.java- Each concept is explained - Experiment with object creation - Try creating your own fruits
- Run simple tests - See how testing validates behavior
- Study inheritance patterns - Compare Apple, Orange, and Banana implementations
- Analyze polymorphism - Trace method calls through the inheritance hierarchy
- Examine the test suite - Understand comprehensive testing strategies
- Try modifications - Add new fruit types or behaviors
- Design patterns - Identify Template Method, Factory, and other patterns
- Extend the system - Add new interfaces, create fruit categories
- Refactor for packages - Split into multiple files and packages
- Add persistence - Save/load fruit data from files or databases
- Create a
Grapeclass that extendsFruit - Add a
colorparameter to thetoString()method output - Make a fruit basket that holds only ripe fruits
- Implement a
Seasonalinterface with availability months - Create a
CitrusFruitabstract class betweenFruitand citrus fruits - Add a
NutritionFactsclass and composition relationship
- Implement the Visitor pattern for fruit operations
- Add generic type parameters for specialized baskets
- Create a fruit processing factory with different product types
- Implement custom serialization for saving/loading fruits
This is an educational project, and contributions that enhance learning are welcome!
- Bug fixes in the existing code
- Additional OOP examples that fit the fruit theme
- More comprehensive tests for edge cases
- Documentation improvements and clearer explanations
- New fruit types demonstrating different OOP concepts
- Alternative implementations showing different design approaches
- Maintain educational focus - All code should teach OOP concepts
- Include comprehensive comments - Explain the "why" not just the "what"
- Add corresponding tests - Maintain 100% test coverage
- Follow existing patterns - Keep consistency with current code style
- Update documentation - Ensure README and CLAUDE.md stay current
- Fork the repository
- Create a feature branch (
git checkout -b feature/new-fruit-type) - Make your changes with full comments and tests
- Verify all tests pass (
java FruitTests) - Submit a pull request with detailed description
This project is created for educational purposes. Feel free to use, modify, and distribute for learning and teaching OOP concepts.
This Fruit OOP example provides a solid foundation for understanding Object-Oriented Programming in Java. The extensive comments, complete test coverage, and practical examples make it an ideal learning resource for students, educators, and anyone looking to master OOP concepts.
Happy Learning! π
For questions, suggestions, or educational use, please refer to the documentation or create an issue in the project repository.