An Abstract Class is more than just a list of required methods; it can also hold shared data. This project demonstrates how to combine an abstract contract (makeSound()) with common state (name). By defining the name field in the Animal base class, we ensure that every inhabitant of our digital farm has an identity. Subclasses like Cat and Cow leverage the parent constructor to initialize this identity while providing their own unique implementation of the sound logic. This approach highlights how inheritance reduces redundancy by centralizing shared attributes.
- Abstract Data Storage: Implemented a
String namefield within the abstractAnimalclass. - Constructor Chaining: Used
super(name)in subclasses to correctly initialize base class fields. - Specialized Implementation: Provided distinct
makeSound()logic forCatandCowthat incorporates their names. - Polymorphic Collection: Managed a diverse set of named animals through a single
Animal[]array.
- Java 8+ (Abstract Classes, Constructors, Inheritance, Polymorphism)
- farm.Animal: The abstract base providing identity (name) and the sound contract.
- Cat: A named feline that meows.
- Cow: A named bovine that moos.
- FarmLauncherApp: The simulation entry point that populates and activates the farm.
Murka: Meow!
Burenka: Moo!
Project Structure:
JavaBasics_Task_323/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── FarmLauncherApp.java
│ └── farm/
│ ├── animals/
│ │ ├── Cat.java
│ │ └── Cow.java
│ └── Animal.java
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.farm.Animal;
import com.yurii.pavlenko.farm.animals.Cat;
import com.yurii.pavlenko.farm.animals.Cow;
public class FarmLauncherApp {
public static void main(String[] args) {
Animal[] animals = new Animal[2];
animals[0] = new Cat("Murka");
animals[1] = new Cow("Burenka");
for (Animal animal : animals) {
animal.makeSound();
}
}
}package com.yurii.pavlenko.farm;
public abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
}package com.yurii.pavlenko.farm.animals;
import com.yurii.pavlenko.farm.Animal;
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + ": Meow!");
}
}package com.yurii.pavlenko.farm.animals;
import com.yurii.pavlenko.farm.Animal;
public class Cow extends Animal {
public Cow(String name) {
super(name);
}
@Override
public void makeSound() {
System.out.println(name + ": Moo!");
}
}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