How can I properly override a superclass’s field in Java?

0
13
Asked By TechyNinja42 On

I'm working with Java and have a superclass called `Super` which has a protected field named `cooldown`. In its constructor, there's a Timer that uses this `cooldown` value. I also have a subclass called `Child` where I want to override the `cooldown` value to 1000, but it doesn't seem to be working as expected. My main goal is to keep `Super`'s constructor intact for use in its child classes. How can I correctly set this field in the `Child` class?

2 Answers

Answered By CodeWhisperer89 On

To fix this, you need to set the `cooldown` variable in the `Child` constructor after calling `super()`. By declaring `cooldown` again in `Child`, you are creating a new variable, not overriding the one in `Super`. Just use `cooldown = 1000;` in the `Child` constructor instead of declaring a new variable. This way, you can access the `cooldown` from `Super` and modify it as needed.

Answered By DevExtraordinaire14 On

It seems like there are a few issues here. First, you don't need to redefine `cooldown` in `Child`; just use the one from `Super` directly. Also, note that the Timer doesn't get updated with the new `cooldown` value if it's set after calling `super()`. If you need a flexible timer, consider designing a utility that creates Timers instead of directly using the Swing Timer, which might not be the best choice for modern applications.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.