The power of Inheritance lies in its ability to create a scalable architecture. This project builds upon the virtual pet world by introducing a Dog class that inherits from the same Animal base class as the previous Cat implementation. This demonstrates Hierarchical Inheritance, where multiple subclasses share a single superclass. Both dogs and cats can sleep, but only dogs can bark, illustrating how specific behaviors are encapsulated within their respective subclasses while sharing common traits.
- Superclass Consistency: Reused the
Animalclass with a sharedpetNamefield andsleep()method. - Hierarchical Inheritance: Created a new
Dogsubclass that extendsAnimalwithout affecting existing code. - Specific Behavior: Implemented a unique
bark()method for theDogclass. - Member Access: Confirmed that
Dogsuccessfully accesses the inheritedpetNamefield. - Clean Architecture: Separated domain models into distinct files, keeping the
DogLauncherAppclean.
- Java 8+ (Inheritance, Polymorphism, Access Modifiers)
- Animal: The superclass providing the
sleep()behavior. - Dog: The specialized subclass with the
bark()behavior. - DogLauncherApp: The entry point to instantiate and test the canine pet.
Sharik is sleeping.
Sharik says: Woof!
Project Structure:
JavaBasics_Task_285/
├── src/
│ └── com/yurii/pavlenko/
│ ├── Animal.java
│ ├── Dog.java
│ └── DogLauncherApp.java
└── README.md
Code
package com.yurii.pavlenko;
public class DogLauncherApp {
public static void main(String[] args) {
Dog dog = new Dog();
dog.petName = "Sharik";
dog.sleep();
dog.bark();
}
}package com.yurii.pavlenko;
public class Animal {
public String petName;
public void sleep() {
System.out.println(petName + " is sleeping.");
}
}package com.yurii.pavlenko;
public class Dog extends Animal {
public void bark() {
System.out.println(petName + " says: Woof!");
}
}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