In Java, Covariant Return Types allow an overriding method to return a subtype of the type returned by the original method in the superclass. This project illustrates this using a "Basket" hierarchy. While a generic Basket provides a generic Fruit, a specialized AppleBasket is guaranteed to provide an Apple. This feature reduces the need for explicit type casting and makes the API of specialized classes much more intuitive and type-safe.
- Class Hierarchy: Established
Fruit->AppleandBasket->AppleBasketrelationships. - Covariant Overriding: Redefined
getFruit()inAppleBasketto returnAppleinstead ofFruit. - Type Verification: Used the
instanceofoperator to confirm the runtime type of the returned object. - Polymorphism: Demonstrated that a specialized return still satisfies the superclass contract.
- Clean Architecture: Strictly separated the domain entities from the
HarvestLauncherApp.
- Java 8+ (Inheritance, Covariant Returns, Type Checking)
- Fruit / Apple: The data models representing the items being harvested.
- Basket / AppleBasket: The factory-like classes demonstrating method specialization.
- HarvestLauncherApp: The bootstrap class for verifying the harvest results.
Apple created
Project Structure:
JavaBasics_Task_291/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── HarvestLauncherApp.java
│ ├── basket/
│ │ ├── applebasket/
│ │ │ └── AppleBasket.java
│ │ └── Basket.java
│ └── fruit/
│ ├── apple/
│ │ └── Apple.java
│ └── Fruit.java
├── .gitignore
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.basket.applebasket.AppleBasket;
import com.yurii.pavlenko.fruit.Fruit;
import com.yurii.pavlenko.fruit.apple.Apple;
public class HarvestLauncherApp {
public static void main(String[] args) {
AppleBasket appleBasket = new AppleBasket();
Fruit harvestedItem = appleBasket.getFruit();
if (harvestedItem instanceof Apple) {
System.out.println("Apple created");
}
}
}package com.yurii.pavlenko.fruit.apple;
import com.yurii.pavlenko.fruit.Fruit;
public class Apple extends Fruit {
// Specific apple properties
}package com.yurii.pavlenko.basket.applebasket;
import com.yurii.pavlenko.basket.Basket;
import com.yurii.pavlenko.fruit.apple.Apple;
public class AppleBasket extends Basket {
@Override
public Apple getFruit() {
return new Apple();
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT