Method overriding (programming)
Encyclopedia
Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

 that is already provided by one of its superclasses or parent classes. The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters
Parameter (computer science)
In computer programming, a parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. These pieces of data are called arguments...

 or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 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. Some languages allow a programmer
Programmer
A programmer, computer programmer or coder is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software. One who practices or professes a formal approach to...

 to prevent a method from being overridden.

C#

C# does support method overriding, but only if explicitly requested with the keywords and .


class Animal {
public String name;
// Methods
public void drink;
public virtual void eat;
public void go;
}

class Cat : Animal {
public new String name;
// Methods
public void drink; // warning: hides inherited drink. Use new
public override void eat; // overwrites inherited eat.
public new void go; // hides inherited go.
}


To make method overriding to occur, the signatures must be identical (with same visibility). In C#, not only class methods can be overridden, but indexer
Indexer (programming)
In programming, an indexer is in object-oriented programming a kind of smart array that enables the user to get an index of objects held within an object. It is a member of a class that enables the use it like an array...

s and properties
Property (programming)
A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field and a method. Properties are read and written like fields, but property reads and writes are translated to get and set method calls...

 as well. As they are only methods of the class and not of the class instances, static methods cannot be overridden.

In addition to requesting keywords to make method overriding possible, C# gives the possibility of hiding an inherited property or method. This is done by using the same signature of a property or method and adding the keyword 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 Animal.eat!
((Animal)cat).go; // calls Animal.go!

C++

C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 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
Scope resolution operator
In computer programming, scope is an enclosing context where values and expressions are associated. The scope resolution operator helps to identify and specify the context to which an identifier refers...

. For example, the following code presents two classes
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

, the base class , and the derived class . overrides the class's method, so as also to print its height.

  1. include


class Rectangle {
public:
explicit 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 = " << this->length << "; Width = " << this->width;
}

class Box : public Rectangle {
public:
explicit Box(double l, double w, double h) : Rectangle(l, w), height(h) {}
virtual void print const; // virtual is optional here, but it is a good practice to remind it to the developer

private:
double height;
};

void Box::print const { // print method of derived class
Rectangle::print; // Invoke parent print method.
std::cout << "; Height= " << this->height;
}


The method in class , by invoking the parent version of method , is also able to output the private variables
Variable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...

  and of the base class. Otherwise, these variables are inaccessible to .

The following statements
Statement (programming)
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal components .Many languages In computer programming...

 will instantiate
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

 objects of type and , and call their respective methods:


int main(int argc, char** argv) {
Rectangle rectangle(5.0, 3.0); rectangle.print;
// outputs:
// Length = 5.0; Width = 3.0

Box box(6.0, 5.0, 4.0);
// the pointer to the most overridden method in the vtable in on Box::print
box.print; // but this call does not illustrate overriding
static_cast(box).print; // this one does
// outputs:
// Length = 5.0; Width = 3.0; Height= 4
}

Eiffel

In Eiffel
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...

, 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
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....

s and postcondition
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 within the code itself...

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.

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
--
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 {THOUGHT}).message;
(create {ADVICE}).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
--
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 (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, when a subclass contains a method that overrides a method of the superclass, it can also invoke the superclass method by using the keyword
Keyword (computer programming)
In computer programming, a keyword is a word or identifier that has a particular meaning to the programming language. The meaning of keywords — and, indeed, the meaning of the notion of keyword — differs widely from language to language....

  (Lewis & Loftus, 2006).
Example:


public class Thought {
public void display_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 display_message {
System.out.println("Warning: Dates in calendar are closer than they appear.");
}
}


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 used to call the superclass's version of the method from the subclass. For example, this variation prints out both messages when the subclass method is called:


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.

Python

In Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, when a subclass contains a method that overrides a method of the superclass, you can also call the superclass method by calling instead of ].
Example:


class Thought(object):
def __init__(self):
pass
def message:
print "I feel like I am diagonally parked in a parallel universe."

class Advice(Thought):
def __init__(self):
Thought.__init__(self)
def message:
print "Warning: Dates in calendar are closer than they appear"
Thought.message(self)

See also

  • Implementation inheritance
  • Inheritance semantics
  • Method overloading
    Method overloading
    Function overloading or method overloading is a feature found in various programming languages such as Ada, C#, VB.NET, C++, D and Java that allows the creation of several methods with the same name which differ from each other in terms of the type of the input and the type of the output of the...

  • Polymorphism in object-oriented programming
    Polymorphism in object-oriented programming
    Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability to create a variable, a function, or an object that has more than one form. The word derives from the Greek "πολυμορφισμός" meaning "having multiple forms"...

  • Template method pattern
    Template method pattern
    In software engineering, the template method pattern is a design pattern.It is a behavioral pattern, and is unrelated to C++ templates.-Introduction:A template method defines the program skeleton of an algorithm...

  • Virtual inheritance
    Virtual inheritance
    Virtual inheritance is a topic of object-oriented programming. It is a kind of inheritance in which the part of the object that belongs to the virtual base class becomes common direct base for the derived class and any next class that derives from it...


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK