No announcement
 

Overriding

Overriding is the ability of the subclass to override (or change) the functionality of an existing method defined in the super class. This allows the define the behaviour which is specific to the subclass, i.e., a subclass can also implement a super class method based on the requirement.

Following are the rules for Method Overriding:

  1. Parameters should be same as that of the overridden method.
  2. Method return type should be the same as that of super class overridden method.
  3. The access level cannot be more restrictive than the super class overridden method's access level.
  4. A method declared as final cannot be overridden.
  5. A method declared as static cannot be overridden, but can be declared again.
  6. A method that cannot be inherited, also cannot be overridden.
  7. A subclass can override any super class method (not final or private), if it is within the same package as that of the instance class. If a subclass is in a different package then it can only override the public or protected non-final methods.
  8. An Instance method can only be overridden if it is inherited by the subclass.
  9. An overriding method can throw any unchecked exceptions. The overriding method can throw narrower or fewer exceptions than the overridden method.
  10. Constructors cannot be overridden.

Example:

OverridingDemo.java

package com.codingnous.tutorial;

public class OverridingDemo {

	public static void main(String[] args) {

		// Employee reference object
		Employee e = new Employee();

		// Employee reference, developer object
		Employee ed = new Developer();

		e.salary();
		ed.salary();

		// This will lead to error as Employee does not have bonus();
		// ed.bonus();
	}
}

class Employee {

	public void salary() {
		System.out.println("Employee base salary.");
	}
}

class Developer extends Employee {

	public void salary() {
		System.out.print("Developer salary.");
	}

	public void bonus() {
		System.out.println("Performance bonus.");
	}
}

Output
Employee base salary. Developer salary.