Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When overriding a method should my custom code come before or after super(base)

Tags:

java

c#

.net

oop

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

like image 824
zachary Avatar asked Feb 25 '11 15:02

zachary


People also ask

What is the rule for overriding?

A rule that overrides one or more other rules is executed in place of the rules that are overridden. Normally, rule overriding operates within a hierarchy of rules, with a local or more specific rule overriding a more general rule.

How do we override a method from the superclass?

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error.

When should you override a method in a subclass?

In Java, method overriding occurs when a subclass (child class) has the same method as the parent class. In other words, method overriding occurs when a subclass provides a particular implementation of a method declared by one of its parent classes.

What would you override a method of a base class?

An override method provides a new implementation of the method inherited from a base class. The method that is overridden by an override declaration is known as the overridden base method. An override method must have the same signature as the overridden base method. override methods support covariant return types.


2 Answers

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.

like image 161
Tony Casale Avatar answered Oct 04 '22 04:10

Tony Casale


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

like image 26
Darin Dimitrov Avatar answered Oct 04 '22 02:10

Darin Dimitrov