Method Overriding
suggest changeMethod overriding is the ability of subtypes to redefine (override) the behavior of their supertypes.
In Java, this translates to subclasses overriding the methods defined in the superclass. In Java, all non-primitive variables are actually references, which are akin to pointers to the location of the actual object in memory. The references only have one type, which is the type they were declared with. However, they can point to an object of either their declared type or any of its subtypes.
When a method is called on a reference, the corresponding method of the actual object being pointed to is invoked.
class SuperType {
public void sayHello(){
System.out.println("Hello from SuperType");
}
public void sayBye(){
System.out.println("Bye from SuperType");
}
}
class SubType extends SuperType {
// override the superclass method
public void sayHello(){
System.out.println("Hello from SubType");
}
}
class Test {
public static void main(String... args){
SuperType superType = new SuperType();
superType.sayHello(); // -> Hello from SuperType
// make the reference point to an object of the subclass
superType = new SubType();
// behaviour is governed by the object, not by the reference
superType.sayHello(); // -> Hello from SubType
// non-overridden method is simply inherited
superType.sayBye(); // -> Bye from SuperType
}
}
Rules to keep in mind
To override a method in the subclass, the overriding method (i.e. the one in the subclass) MUST HAVE:
- same name
- the same return type for primitives (a subtype is allowed for reference types; these are covariant return types)
- the same type and order of parameters
- it may not be less accessible than the superclass method
- it may throw only those checked exceptions that are declared in the throws clause of the superclass’s method, or subclasses of those exceptions. It may also choose not to throw any checked exception. Parameter names do not matter. For example,
void methodX(int i)is the same asvoid methodX(int k) finalmethods cannot be overridden. Astaticmethod with the same signature hides the superclass method; it does not override it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents