In Java inheritance, when a subclass declares a field with the same name as a field in its superclass, the subclass field shadows the parent field. This project explores how to navigate this conflict using the super keyword. While the Cat class has its own name, the original name from the Animal class remains part of the object's state. Understanding shadowing is crucial for debugging complex hierarchies where variable names might overlap across different levels of inheritance.
- Field Shadowing: Declared identical field names in both
AnimalandCatclasses. - Explicit Access: Used
super.nameto bypass the local scope and reach the parent's data. - State Preservation: Demonstrated that both values coexist within a single object instance.
- Professional Packaging: Applied strict package separation between domain models and the application entry point.
- Java 8+ (Inheritance, Field Shadowing, 'super' keyword)
- Animal: The superclass with the base
namefield. - Cat: The subclass that shadows the field and provides a reporting method.
- GenealogyLauncherApp: The bootstrap class to execute the comparison.
Name from Cat: Cat
Name from Animal: Animal
Project Structure:
JavaBasics_Task_294/
├── src/
│ └── com/yurii/pavlenko/
│ ├── app/
│ │ └── GenealogyLauncherApp.java
│ └── animal/
│ ├── cat/
│ │ └── Cat.java
│ └── Animal.java
├── LICENSE
├── TASK.md
├── THEORY.md
└── README.md
Code
package com.yurii.pavlenko.app;
import com.yurii.pavlenko.animal.cat.Cat;
public class GenealogyLauncherApp {
public static void main(String[] args) {
Cat cat = new Cat();
cat.printNames();
}
}package com.yurii.pavlenko.animal;
public class Animal {
public String name = "Animal";
}package com.yurii.pavlenko.animal.cat;
import com.yurii.pavlenko.animal.Animal;
public class Cat extends Animal {
public String name = "Cat";
public void printNames() {
System.out.println("Name from Cat: " + name);
System.out.println("Name from Animal: " + super.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