When overriding a method should my custom code come before or after the super(base) call to the parent class?
相关问题
- Delete Messages from a Topic in Apache Kafka
- how to define constructor for Python's new Nam
- Jackson Deserialization not calling deserialize on
- Sorting 3 numbers without branching [closed]
- How to maintain order of key-value in DataFrame sa
This will depend on when you want your code to execute: before or after the base method.
The dependencies of your subclass instance variables with respect to your superclass parameters will determine where your code goes (Java):
There are 3 choices you have here:
It is important to also check your API's documentation. Some classes have subclass contracts that are not enforcable by code, but that can break behavior if you don't follow their rules. There are some cases where subclasses are required to call the super implementation.
It depends on You want to make something before or after orginal method. Good practise is to write custom code after super call. That becase you ADD some new code.
It depends of the behavior you want. You don't even have to call super's method at all. The place you call it will depend if you want your code executed before or after the base class code.
Like most things, the simple answer is: it depends.
Specifying super or base allows you to "extend" the method, by adding functionality to what already exists in the base implementation. That code may need to be performed before, after, or on both sides of the call to the base functionality. It all comes down to what your overridden implementation needs to do above and beyond the base implementation.
There are some places, at least in C#, where you cannot choose. For instance, constructors of derived classes in C# have to define a base constructor in their declaration (the default is the parameterless constructor if one exists). The code of the base class is ALWAYS executed BEFORE the derived class, and you can't simply call
base(x,y)
from within the constructor.