java
Force a subclass to “implement” the value of a field [duplicate]
This question already has an answer here: How to get around the lack of abstract fields in Java? 5 answers I have a Button baseclass in Java and several types of button subclasses that inherit from this class. The Button baseclass looks like this: public abstract class BaseButton extends AppCompatButton{ private ButtonStatus buttonStatus = ButtonStatus.OFF; private Image onIcon; private Image offIcon; public void toggleButton(){ if(this.buttonStatus == ButtonStatus.ON){ this.buttonStatus = ButtonStatus.OFF; setBackgroundResource(offIcon); }else if(this.buttonStatus == ButtonStatus.OFF){ this.buttonStatus = ButtonStatus.ON; setBackgroundResource(onIcon); } } } I want each Button subclass to be able to call the toggleButton() method, but each of them have a different onIcon and offIcon field. Since I am using these fields in the superclass, I need to have them declared there as well, and they are both instantiated to null. So whenever I call the toggleButton() method from a subclass, the null values are used from the superclass. However, I would like to implement this method in the superclass (to avoid code duplication), but still use the subclasses fields. How can I achieve this?
pass both icons as parameter to the superclass: public abstract class BaseButton extends AppCompatButton{ private ButtonStatus buttonStatus = ButtonStatus.OFF; private Image onIcon; private Image offIcon; public BaseButton (Image onIcon, Image offIcon){ this.onIcon = onIcon; this.offIcon = offIcon; } public void toggleButton(){ // ... and in the Subclass public class SubButton extends BaseButton { public SubButton () { super(IconSet.SUB_BUTTON_ICON_ON,IconSet.SUB_BUTTON_ICON_OFF); } // more code
Related Links
How to split the text using selenium webdriver? [closed]
How do I get my server to print the input from my client class?
Android Paginated Map Bad Performance
Saving a dinamic SQL query to CSV?
Exception from GenericFilterBean are not catched with global exception handler #ControllerAdvice
Replace a different and many characters or word's to single word in multiple Java files in different scenarios
How to get a generic response from retrofit
Blocking nested-loops iterator
How to exit while loop for JOptionPane when user clicks no?
Visitor Pattern for Interpreter - Invoking method based on instance type
javafx snapshot with slow performance
How do I output the contents of a specific row from a CSV file?
Enforcing Coding standards for Github repositories across team
Gson same serialize name with retrofit
How to count mutual words in 2 strings in Java? [duplicate]
Looking for log analyser for monitoring, trace logs with checkpoints and unique request ids