"Struggling with Java Inheritance and Method Overriding: Need Help Understanding Behavior
0

Hi everyone,

I'm working on a Java project and facing some confusion regarding method overriding and inheritance. Specifically, I’m trying to understand how the subclass behaves when overriding methods from a superclass, and I'm not sure why my code is behaving the way it is.

Here's my example:

  1. I have a base class with a method.

  2. I override that method in a subclass.

  3. When I instantiate the subclass and call the method, I expect the subclass's overridden version, but the output is not as expected.

Could someone help explain why this is happening or what I might be doing wrong?

Any help or suggestions would be greatly appreciated!

class Animal {
    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal animal = new Animal();
        animal.makeSound();  // Should print: Animal makes a sound

        Animal dog = new Dog();
        dog.makeSound();  // Should print: Dog barks (but it doesn't)
    }
}

 


Anonymous May 10, 2025 12:31 67 views

0 Answers

No answers yet. Be the first to post an answer!
You need to sign in to post an answer.
Need More Help?

Get personalized assistance with your technical questions.