Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Method overriding
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Language-specific examples== ===Ada=== [[Ada (programming language)|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. <syntaxhighlight lang="Ada"> 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 </syntaxhighlight> ===C#=== [[C Sharp (programming language)|C#]] does support method overriding, but only if explicitly requested using the modifiers {{C sharp|override}} and {{C sharp|virtual}} or {{C sharp|abstract}}. [[File:Csharp method overriding.svg]] <syntaxhighlight lang="csharp"> abstract class Animal { public string Name { get; set; } // Methods public void Drink(); public virtual void Eat(); public void Go(); } class Cat : Animal { public new string Name { get; set; } // Methods public void Drink(); // Warning: hides inherited drink(). Use new public override void Eat(); // Overrides inherited eat(). public new void Go(); // Hides inherited go(). } </syntaxhighlight> When overriding one method with another, the [[Type signature|signatures]] of the two methods must be identical (and with same visibility). In C#, [[class method]]s, [[Indexer (programming)|indexer]]s, [[Property (programming)|properties]] 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 {{C sharp|new}} in front of it.<ref>{{cite web | accessdate = 2011-08-02 | date = 2002-03-25 | first = Hanspeter | last = Mössenböck | pages = 6–8 | publisher = Institut für Systemsoftware, Johannes Kepler Universität Linz, Fachbereich Informatik | title = Advanced C#: Overriding of Methods | quote = | url = http://ssw.jku.at/Teaching/Lectures/CSharp/Tutorial/Part2.pdf}} </ref> In the above example, hiding causes the following: <syntaxhighlight lang="csharp"> 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()! </syntaxhighlight> ===C++=== [[C++]] does not have the keyword {{Cpp|super}} that a subclass can use in Java to invoke the 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 [[Class (computer science)|classes]], the base class {{Cpp|Rectangle}}, and the derived class {{Cpp|Box}}. {{Cpp|Box}} overrides the {{Cpp|Rectangle}} class's {{Cpp|Print}} method, so as also to print its height.<ref name="malik">Malik 2006, p. 676</ref> <syntaxhighlight lang="cpp"> #include <iostream> //--------------------------------------------------------------------------- class Rectangle { public: Rectangle(double l, double w) : length_(l), width_(w) {} virtual void Print() const; private: double length_; double width_; }; //--------------------------------------------------------------------------- void Rectangle::Print() const { // Print method of base class. std::cout << "Length = " << length_ << "; Width = " << width_; } //--------------------------------------------------------------------------- class Box : public Rectangle { public: Box(double l, double w, double h) : Rectangle(l, w), height_(h) {} void Print() const override; private: double height_; }; //--------------------------------------------------------------------------- // Print method of derived class. void Box::Print() const { // Invoke parent Print method. Rectangle::Print(); std::cout << "; Height = " << height_; } </syntaxhighlight> The method {{Cpp|Print}} in class {{Cpp|Box}}, by invoking the parent version of method {{Cpp|Print}}, is also able to output the private [[Variable (programming)|variables]] {{Cpp|length}} and {{Cpp|width}} of the base class. Otherwise, these variables are inaccessible to {{Cpp|Box}}. The following [[Statement (programming)|statements]] will [[Object (computer science)|instantiate]] objects of type {{Cpp|Rectangle}} and {{Cpp|Box}}, and call their respective {{Cpp|Print}} methods: <syntaxhighlight lang="cpp"> int main(int argc, char** argv) { Rectangle rectangle(5.0, 3.0); // Outputs: Length = 5.0; Width = 3.0 rectangle.Print(); Box box(6.0, 5.0, 4.0); // The pointer to the most overridden method in the vtable in on Box::print, // but this call does not illustrate overriding. box.Print(); // This call illustrates overriding. // outputs: Length = 6.0; Width = 5.0; Height= 4.0 static_cast<Rectangle&>(box).Print(); } </syntaxhighlight> In [[C++11]], similar to Java, a method that is declared <code>final</code> in the super class cannot be overridden; also, a method can be declared <code>override</code> to make the compiler check that it overrides a method in the base class. ===Delphi=== In [[Delphi (programming language)|Delphi]], 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 <syntaxhighlight lang="pascal"> 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; </syntaxhighlight> ===Eiffel=== In [[Eiffel (programming language)|Eiffel]], '''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]]s and [[postcondition]]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.<ref name="meyer">Meyer 2009, page 572-575</ref> The intent to redefine a feature, as {{Eiffel|message}} in the example below, must be explicitly declared in the {{Eiffel|inherit}} clause of the heir class. <syntaxhighlight lang="eiffel"> 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 </syntaxhighlight> In class {{Eiffel|ADVICE}} the feature {{Eiffel|message}} is given an implementation that differs from that of its precursor in class {{Eiffel|THOUGHT}}. Consider a class which uses instances for both {{Eiffel|THOUGHT}} and {{Eiffel|ADVICE}}: <syntaxhighlight lang="eiffel"> class APPLICATION create make feature make -- Run application. do (create {THOUGHT}).message; (create {ADVICE}).message end end </syntaxhighlight> When instantiated, class {{Eiffel|APPLICATION}} produces the following output: <syntaxhighlight lang="output"> I feel like I am diagonally parked in a parallel universe. Warning: Dates in calendar are closer than they appear. </syntaxhighlight> Within a redefined feature, access to the feature's precursor can be gained by using the language keyword {{Eiffel|Precursor}}. Assume the implementation of {{Eiffel|{ADVICE}.message}} is altered as follows: <syntaxhighlight lang="eiffel"> message -- Precursor do print ("Warning: Dates in calendar are closer than they appear.%N") Precursor end </syntaxhighlight> Invocation of the feature now includes the execution of {{Eiffel|{THOUGHT}.message}}, and produces the following output: <syntaxhighlight lang="output"> Warning: Dates in calendar are closer than they appear. I feel like I am diagonally parked in a parallel universe. </syntaxhighlight> ===Java=== In [[Java (programming language)|Java]], when a subclass contains a method with the same signature (name and parameter types) as a method in its superclass, then the subclass's method overrides that of the superclass. For example: <syntaxhighlight lang="java"> class Thought { public void message() { System.out.println("I feel like I am diagonally parked in a parallel universe."); } } public class Advice extends Thought { @Override // @Override annotation in Java 5 is optional but helpful. public void message() { System.out.println("Warning: Dates in calendar are closer than they appear."); } } </syntaxhighlight> Class {{Java|Thought}} represents the superclass and implements a method call {{Java|message()}}. The subclass called {{Java|Advice}} inherits every method that could be in the {{Java|Thought}} class. Class {{Java|Advice}} overrides the method {{Java|message()}}, replacing its functionality from {{Java|Thought}}. <syntaxhighlight lang="java"> 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." </syntaxhighlight> When a subclass contains a method that overrides a method of the superclass, then that (superclass's) overridden method can be explicitly invoked from within a subclass's method by using the [[Keyword (computer programming)|keyword]] {{Java|super}}.<ref name="lewis-loftus" /> (It cannot be explicitly invoked from any method belongings to a class that is unrelated to the superclass.) The {{Java|super}} reference can be <syntaxhighlight lang="Java"> 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. } </syntaxhighlight> 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.<ref name="deitel">Deitel & Deitel 2001, p.474</ref> === Kotlin === In [[Kotlin (programming language)|Kotlin]] we can simply override a function like this (note that the function must be {{java|open}}): <syntaxhighlight lang="kotlin"> 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") } </syntaxhighlight> ===Python=== In [[Python (programming language)|Python]], when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling {{Python|super(Subclass, self).method}}<ref name="python-3-super">{{Python|super().method}} in Python 3 - see https://docs.python.org/3/library/functions.html#super {{Webarchive|url=https://web.archive.org/web/20181026035007/https://docs.python.org/3/library/functions.html#super |date=2018-10-26 }}</ref> instead of {{Python|self.method}}. Example: <syntaxhighlight lang="python"> 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 </syntaxhighlight> ===Ruby=== In [[Ruby (programming language)|Ruby]] 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: <syntaxhighlight lang="ruby"> 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 </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)