
Method overriding, in
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, is a language feature that allows a
subclass or child class to provide a specific implementation of a
method that is already provided by one of its
superclasses or parent classes. In addition to providing data-driven algorithm-determined parameters across virtual network interfaces, it also allows for a specific type of
polymorphism
Polymorphism, polymorphic, polymorph, polymorphous, or polymorphy may refer to:
Computing
* Polymorphism (computer science), the ability in programming to present the same programming interface for differing underlying forms
* Ad hoc polymorphis ...
(
subtyping
In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, ...
). The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same
parameters
A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
or signature, and same return type as the method in the parent class.
[Flanagan 2002, p. 107] The version of a method that is executed will be determined by the
object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.
[Lewis & Loftus 2006, p.454] This helps in preventing problems associated with differential relay analytics which would otherwise rely on a framework in which method overriding might be obviated. Some languages allow a
programmer
A computer programmer, sometimes referred to as a software developer, a software engineer, a programmer or a coder, is a person who creates computer programs — often for larger computer software.
A programmer is someone who writes/creates ...
to prevent a method from being overridden.
Language-specific examples
Ada
Ada provides method overriding by default.
To favor early error detection (e.g. a misspelling),
it is possible to specify when a method
is expected to be actually overriding, or not. That will be checked by the compiler.
type T is new Controlled with ......;
procedure Op(Obj: in out T; Data: in Integer);
type NT is new T with null record;
overriding -- overriding indicator
procedure Op(Obj: in out NT; Data: in Integer);
overriding -- overriding indicator
procedure Op(Obj: in out NT; Data: in String);
-- ^ compiler issues an error: subprogram "Op" is not overriding
C#
C# does support method overriding, but only if explicitly requested using the modifiers and or .
abstract class Animal
class Cat : Animal
When overriding one method with another, the
signatures
A signature (; from la, signare, "to sign") is a handwritten (and often stylized) depiction of someone's name, nickname, or even a simple "X" or other mark that a person writes on documents as a proof of identity and intent. The writer of a ...
of the two methods must be identical (and with same visibility). In C#,
class method
A method in object-oriented programming (OOP) is a procedure associated with a message and an object. An object consists of ''state data'' and ''behavior''; these compose an ''interface'', which specifies how the object may be utilized by any of ...
s,
indexers,
properties
Property is the ownership of land, resources, improvements or other tangible objects, or intellectual property.
Property may also refer to:
Mathematics
* Property (mathematics)
Philosophy and science
* Property (philosophy), in philosophy an ...
and events can all be overridden.
Non-virtual or static methods cannot be overridden. The overridden base method must be ''virtual'', ''abstract'', or ''override''.
In addition to the modifiers that are used for method overriding, C# allows the hiding of an inherited property or method. This is done using the same signature of a property or method but adding the modifier in front of it.
[
]
In the above example, hiding causes the following:
Cat cat = new Cat();
cat.Name = …; // accesses Cat.Name
cat.Eat(); // calls Cat.Eat()
cat.Go(); // calls Cat.Go()
((Animal)cat).Name = …; // accesses Animal.Name!
((Animal)cat).Eat(); // calls Cat.Eat()!
((Animal)cat).Go(); // calls Animal.Go()!
C++
C++ does not have the keyword that a subclass can use in Java to invoke a superclass version of a method that it wants to override. Instead, the name of the parent or base class is used followed by the
scope resolution operator. For example, the following code presents two
classes, the base class , and the derived class . overrides the class's method, so as also to print its height.
[Malik 2006, p. 676]
#include
//---------------------------------------------------------------------------
class Rectangle ;
//---------------------------------------------------------------------------
void Rectangle::Print() const
//---------------------------------------------------------------------------
class Box : public Rectangle ;
//---------------------------------------------------------------------------
// Print method of derived class.
void Box::Print() const
The method in class , by invoking the parent version of method , is also able to output the private
variables and of the base class. Otherwise, these variables are inaccessible to .
The following
statements
Statement or statements may refer to: Common uses
* Statement (computer science), the smallest standalone element of an imperative programming language
*Statement (logic), declarative sentence that is either true or false
*Statement, a declarativ ...
will
instantiate
Instantiation or instance may refer to:
Philosophy
* A modern concept similar to ''participation'' in classical Platonism; see the Theory of Forms
* The instantiation principle, the idea that in order for a property to exist, it must be had b ...
objects of type and , and call their respective methods:
int main(int argc, char** argv)
In
C++11
C++11 is a version of the ISO/ IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versio ...
, similar to Java, a method that is declared
final
in the super class cannot be overridden; also, a method can be declared
override
to make the compiler check that it overrides a method in the base class.
Delphi
In
Delphi
Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracl ...
, method overriding is done with the directive override, but only if a method was marked with the dynamic or virtual directives.
The inherited reserved word must be called when you want to call super-class behavior
type
TRectangle = class
private
FLength: Double;
FWidth: Double;
public
property Length read FLength write FLength;
property Width read FWidth write FWidth;
procedure Print; virtual;
end;
TBox = class(TRectangle)
public
procedure Print; override;
end;
Eiffel
In
Eiffel
Eiffel may refer to:
Places
* Eiffel Peak, a summit in Alberta, Canada
* Champ de Mars – Tour Eiffel station, Paris, France; a transit station
Structures
* Eiffel Tower, in Paris, France, designed by Gustave Eiffel
* Eiffel Bridge, Ungheni, ...
, feature redefinition is analogous to method overriding in C++ and Java. Redefinition is one of three forms of feature adaptation classified as redeclaration. Redeclaration also covers effecting, in which an implementation is provided for a feature which was deferred (abstract) in the parent class, and undefinition, in which a feature that was effective (concrete) in the parent becomes deferred again in the heir class. When a feature is redefined, the feature name is kept by the heir class, but properties of the feature such as its signature, contract (respecting restrictions for
precondition
In computer programming, a precondition is a condition or predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification.
If a precondition is violated, the effect of th ...
s and
postcondition In computer programming, a postcondition is a condition or predicate that must always be true just after the execution of some section of code or after an operation in a formal specification. Postconditions are sometimes tested using assertions wit ...
s), and/or implementation will be different in the heir. If the original feature in the parent class, called the heir feature's precursor, is effective, then the redefined feature in the heir will be effective. If the precursor is deferred, the feature in the heir will be deferred.
[Meyer 2009, page 572-575]
The intent to redefine a feature, as in the example below, must be explicitly declared in the clause of the heir class.
class
THOUGHT
feature
message
-- Display thought message
do
print ("I feel like I am diagonally parked in a parallel universe.%N")
end
end
class
ADVICE
inherit
THOUGHT
redefine
message
end
feature
message
-- Precursor
do
print ("Warning: Dates in calendar are closer than they appear.%N")
end
end
In class the feature is given an implementation that differs from that of its precursor in class .
Consider a class which uses instances for both and :
class
APPLICATION
create
make
feature
make
-- Run application.
do
(create ).message;
(create ).message
end
end
When instantiated, class produces the following output:
I feel like I am diagonally parked in a parallel universe.
Warning: Dates in calendar are closer than they appear.
Within a redefined feature, access to the feature's precursor can be gained by using the language keyword . Assume the implementation of is altered as follows:
message
-- Precursor
do
print ("Warning: Dates in calendar are closer than they appear.%N")
Precursor
end
Invocation of the feature now includes the execution of , and produces the following output:
Warning: Dates in calendar are closer than they appear.
I feel like I am diagonally parked in a parallel universe.
Java
In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, when a subclass contains a method that overrides a method of the superclass, it can also invoke the superclass method by using the
keyword .
Example:
class Thought
public class Advice extends Thought
Class represents the superclass and implements a method call . The subclass called inherits every method that could be in the class. However, class overrides the method , replacing its functionality from .
Thought parking = new Thought();
parking.message(); // Prints "I feel like I am diagonally parked in a parallel universe."
Thought dates = new Advice(); // Polymorphism
dates.message(); // Prints "Warning: Dates in calendar are closer than they appear."
The reference can be
public class Advice extends Thought {
@Override
public void message() {
System.out.println("Warning: Dates in calendar are closer than they appear.");
super.message(); // Invoke parent's version of method.
}
There are methods that a subclass cannot override. For example, in Java, a method that is declared final in the super class cannot be overridden. Methods that are declared private or static cannot be overridden either because they are implicitly final. It is also impossible for a class that is declared final to become a super class.
[Deitel & Deitel 2001, p.474]
Kotlin
In
Kotlin we can simply override a function like this (note that the function must be ):
fun main() {
val p = Parent(5)
val c = Child(6)
p.myFun()
c.myFun()
}
open class Parent(val a : Int) {
open fun myFun() = println(a)
}
class Child(val b : Int) : Parent(b) {
override fun myFun() = println("overrided method")
}
Python
In
Python, when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling
[ in Python 3 - see https://docs.python.org/3/library/functions.html#super ] instead of .
Example:
class Thought:
def __init__(self) -> None:
print("I'm a new object of type Thought!")
def message(self) -> None:
print("I feel like I am diagonally parked in a parallel universe.")
class Advice(Thought):
def __init__(self) -> None:
super(Advice, self).__init__()
def message(self) -> None:
print("Warning: Dates in calendar are closer than they appear")
super(Advice, self).message()
t = Thought()
# "I'm a new object of type Thought!"
t.message()
# "I feel like I am diagonally parked in a parallel universe.
a = Advice()
# "I'm a new object of type Thought!"
a.message()
# "Warning: Dates in calendar are closer than they appear"
# "I feel like I am diagonally parked in a parallel universe.
# ------------------
# Introspection:
isinstance(t, Thought)
# True
isinstance(a, Advice)
# True
isinstance(a, Thought)
# True
Ruby
In
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling super in that overridden method. You can use alias if you would like to keep the overridden method available outside of the overriding method as shown with 'super_message' below.
Example:
class Thought
def message
puts "I feel like I am diagonally parked in a parallel universe."
end
end
class Advice < Thought
alias :super_message :message
def message
puts "Warning: Dates in calendar are closer than they appear"
super
end
end
Notes
See also
*
Implementation inheritance
*
Inheritance semantics
*
Method overloading
In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that f ...
*
Polymorphism in object-oriented programming
In programming language theory and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.: "Polymorphic types are types whose operation ...
*
Template method pattern
In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book '' Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defin ...
*
Virtual inheritance
*
X-HTTP-Method-Override HTTP Header
References
* Deitel, H. M & Deitel, P. J.(2001). ''Java How to Program'' (4th ed.). Upper Saddle River, NJ: Prentice Hall.
* Lewis, J. & Loftus, W. (2008). ''Java: Software Solutions'' (6th ed.). Boston, MA: Pearson Addison Wesley.
* Malik, D. S.(2006). ''C++ Programming: Program Design Including Data Structure.'' (3rd ed.). Washington, DC: Course Technology.
* Flanagan, David.(2002).''Java in a Nutshell.''Retrieved from http://oreilly.com/catalog/9780596002831/preview#preview
*
Meyer, Bertrand (2009). ''Touch of Class: Learning to Program Well with Objects and Contracts''. Springer.
External links
Java Method Overridingby Hemanth Balaji
Introduction to O.O.P. Concepts and Moreby Nirosh L.w.C.
by
Sun Microsystems
Sun Microsystems, Inc. (Sun for short) was an American technology company that sold computers, computer components, software, and information technology services and created the Java programming language, the Solaris operating system, ZFS, ...
{{DEFAULTSORT:Method Overriding
Articles with example C++ code
Articles with example code
Articles with example Java code
Method (computer programming)