"Struggling with Java Inheritance and Method Overriding: Need Help Understanding Behavior
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:
-
I have a base class with a method.
-
I override that method in a subclass.
-
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)
}
}
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.