When overriding a method should my custom code com

2019-07-18 16:21发布

When overriding a method should my custom code come before or after the super(base) call to the parent class?

标签: c# java .net oop
6条回答
女痞
2楼-- · 2019-07-18 16:27

This will depend on when you want your code to execute: before or after the base method.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-07-18 16:33

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());
}
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-07-18 16:38

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.

查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-18 16:39

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.

查看更多
叼着烟拽天下
6楼-- · 2019-07-18 16:46

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.

查看更多
我想做一个坏孩纸
7楼-- · 2019-07-18 16:49

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.

查看更多
登录 后发表回答