Method Override (Java / Python)
Java
In Java, when a subclass contains a method that overrides a method of the superclass, it
can also invoke the superclass method by using the keyword super (Lewis & Loftus,
2006).[2] Example:
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.");
}
}
Class Thought represents the superclass and implements a method call message(). The
subclass called Advice inherits every method that could be in the Thought class.
However, class Advice overrides the method message(), replacing its functionality
from Thought.
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 super 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.
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 super(Subclass, self).method[7]instead of self.method. Example:
class Thought(object):
def __init__(self):
pass
def message(self):
print "I feel like I am diagonally parked in a parallel
universe."
class Advice(Thought):
def __init__(self):
super(Advice, self).__init__()
def message(self):
print "Warning: Dates in calendar are closer than they
appear"
super(Advice, self).message()