In software development, we often encounter situations where we need to modify the behavior of a single object without creating a whole new class hierarchy. This project demonstrates Anonymous Inner Classes. We take a base class MagicalCreature and override its makeSound() method during instantiation. This approach is highly efficient for "one-off" logic, keeping the codebase clean and localized.
- Base Class Implementation: Created
MagicalCreaturewith a defaultmakeSound()method. - Anonymous Overriding: Used the
new ClassName() { ... }syntax to redefine behavior at the point of creation. - Dynamic Behavior: Successfully replaced the generic sound with a unique "Croak-croak!" message.
- Encapsulation: Demonstrated that specific behavior can be tied to a single instance.
- Java 8+ (Anonymous Inner Classes, Method Overriding, Polymorphism)
- MagicalCreature: The base class providing the blueprint.
- CreatureApp: The entry point where the anonymous class is defined and executed.
Croak-croak!
Project Structure:
JavaBasics_Task_272/
├── src/
│ └── com/yurii/pavlenko/
│ ├── MagicalCreature.java
│ └── CreatureApp.java
└── README.md
Code
package com.yurii.pavlenko;
public class CreatureApp {
public static void main(String[] args) {
MagicalCreature uniqueCreature = new MagicalCreature() {
@Override
public void makeSound() {
System.out.println("Croak-croak!");
}
};
uniqueCreature.makeSound();
}
}package com.yurii.pavlenko;
public class MagicalCreature {
public void makeSound() {
System.out.println("The creature makes a sound.");
}
}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