Manually instantiating objects can lead to rigid code structures. This project explores Constructor References, a specialized form of method reference that points to a class constructor. By binding the AnimalFactory interface to the Animal : : new reference, we decouple the logic of "when to create" from "how to create". This approach is essential for modern Java patterns, such as the Abstract Factory and the use of Collectors in Stream API.
- Dynamic Factory: Created the
AnimalFactoryinterface to serve as an object creation contract. - Constructor Binding: Used the
Animal : : newsyntax to implement the factory method concisely. - Object State: Ensured the
Animalclass properly initializes itsnamefield via constructor. - Functional Validation: Successfully created and verified a pet named "Barsik".
- Java 8+ (Constructor References, Functional Interfaces)
- Animal: The base class representing a pet with a name.
- AnimalFactory: A functional interface that acts as a blueprint for creating animals.
- PetLauncherApp: The entry point that executes the "birth" of a new virtual pet.
Pet name: Barsik
Project Structure:
JavaBasics_Task_372/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── PetLauncherApp.java
│ └── pet/
│ ├── contracts/
│ │ └── AnimalFactory.java
│ └── models/
│ └── Animal.java
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.pet.contracts.AnimalFactory;
import com.yurii.pavlenko.pet.models.Animal;
public class PetLauncherApp {
public static void main(String[] args) {
AnimalFactory factory = Animal::new;
Animal pet = factory.create("Barsik");
System.out.println("Pet name: " + pet.getName());
}
}package com.yurii.pavlenko.pet.contracts;
import com.yurii.pavlenko.pet.models.Animal;
@FunctionalInterface
public interface AnimalFactory {
Animal create(String name);
}package com.yurii.pavlenko.pet.models;
public class Animal {
private final String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
}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