When overriding a method should my custom code come before or after the super(base) call to the parent class?
问题:
回答1:
There are 3 choices you have here:
- If you want to execute the base behavior before your code, then call it before.
- If you want to execute the base behavior after your code, then call it after.
- If you want to completely override the base behavior, don't call it at all.
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.
回答2:
This will depend on when you want your code to execute: before or after the base method.
回答3:
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.
回答4:
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.
回答5:
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.
回答6:
The dependencies of your subclass instance variables with respect to your superclass parameters will determine where your code goes (Java):
private final Baz baz;
public SubClass(Foo foo, Bar bar) {
Qux qux = QuxFactory.getQuxForFoo(foo);
super(bar, qux);
/* getSize() is a method defined on our super class */
baz = BazFactory.getBazOfSize(getSize());
}