Java Method Override

A class inheriting the method from its superclass has the option to override it. The benefit of overriding is the ability to define behavior specific to a particular class. In the case of a concrete subclass, it is forced to implement all methods defined in abstract class if no other superclass implemented it in the hierarchy. Overriding sometimes referred to as Runtime Binding. It means which overridden method is to be invoked will be determined by reference type and not the instance type.


 

Method Overriding Example

public class ParentClass
{
public void show()
{
System.out.println("Show method of Super class");
}
}

public class SubClass extends ParentClass
{
//below method is overriding the ParentClass version of show method
public void show()
{
System.out.println("Show method of Sub class");
}
}

 

Method Override Rules

  • The overriding method can not have more restrictive access modifier than the method being overridden but it can be less.
  • The argument list must exactly match that of the overridden method, if they don’t it is more likely that you are overloading the method.
  • Return type must be the same as, or a subtype of the return type declared in the overridden method in Superclass.
  • The overriding method can throw any unchecked exception(Runtime) but it can throw checked exception which is broader or new than those declared by the overridden method but it can not throw fewer or narrow checked exception.
  • A final method can not be overridden.
  • Static methods can not be overridden. The static method looks to override but it is hidden.
  • If a method cannot be inherited then it cannot be overridden.

Invoke the Overridden method from Superclass

What if you want to invoke a superclass overridden method before executing the subclass method. You can use SUPER keyword.

public class SubClass extends superclass {

	void method() {
		super.method();
		System.out.println("In Sub Class");
	}

	public static void main(String[] args) {
		SubClass obj = new SubClass();
		obj.method();
	}
}

class superclass {
	void method() {
		System.out.println("In Super Class");
	}
}

Output

In Super Class
In Sub Class

 

Static Method cannot be overridden

A static method can not be overridden. It might look like it is overridden but it is not. A static method can be hidden.

public class SubClass extends superclass {

	static void method() {
		// super.method(); // Super keyword will not work here. As it is not overriden method
		System.out.println("In Sub Class");
	}

	@SuppressWarnings("static-access") // The static method method() from the type SubClass should be accessed in a static way
	public static void main(String[] args) {
		SubClass obj = new SubClass();
		obj.method();
                SubClass.method();// It is same as above. Same method will be invoked
	}
}

class superclass {
	static void method() {
		System.out.println("In Super Class");
	}
}

Here super keyword cannot be used to invoke superclass method. As it is not overridden a method from the superclass.

Cheat-sheet

  • A constructor cannot be overridden.
  • Overriding methods must have the same argument set.
  • Overridden methods must have the same return type. These return type can also be the subclass(covariant return).
  • An overridden method cannot have a more restrictive access modifier.
  • An overridden method cannot throw new or broader exception(Checked). Look below example
  • An overridden method can throw any unchecked exception.
  • Final methods cannot be overridden.
  • Private methods are not inherited to subclass hence it cannot be overridden in a subclass.
  • Polymorphism applies to override.
  • Object type determines which overridden method will be invoked and that will be decided at the runtime.

 

Method Overriding Exception Example

package com.example.simple;

public class Overridding_Class extends base_class {

    @Override
    void method() throws exception_3 {  // NO PROBLEM, It is not a broader Exception.
    }

    void method1() throws exception_1 {   // It will give COMPILATION ERROR as it is throwing Broader Exception
    }
}

class base_class {
    void method() throws exception_2 {
    }

    void method1() throws exception_2 {
    }
}


class excepion_1 extends Exception {
}

class exception_2 extends excepion_1 {
}

class exception_3 extends exception_2 {
}

 

 

Method Overriding Example

package com.override;

public class MethodOverrideRule {

	public static void main(String args[])
	{
		// Here reference type and Object type is same
		MethodOverrideRule scls = new MethodOverrideRule();
		OverrideSubclass subcls = new OverrideSubclass();

		// Here reference type is of Super class and Object is of child class
		MethodOverrideRule subOcls = new OverrideSubclass();

		// This will invoke method from Super class
		scls.method();
		// This will onvoke method form sub class
		subcls.method();

		/*
		 * Here overriding will work. Even reference type is of Super class still object type if of Subclass.
		 * Hence Subclass version of method will get invoked.
		 */
		subOcls.method();

		/*
		 * Which overridden method is to be executed depends on the actual Object type at run time.
		 */
	}

	void method(){
		System.out.println("Overriding method without argument in Super");
	}

	int method(String str)
	{
		System.out.println("Overriding method with int argument in Super");
		return 9;
	}
}

class OverrideSubclass extends MethodOverrideRule{

	/*
	 * Here we are overriding the method from super class.
	 * @Override annotation is used to confirm the same. It makes sure the all override rules get followed 
	 * 
	 */
	@Override
	void method(){
		System.out.println("Overriding method without argument in subclass");
	}

	@Override
	int method(String str)
	{
		System.out.println("Overriding method with int argument in subclass");
		return 10;
	}
}

 

<< Overloading in java Interface in java >>

11 Comments Java Method Override

  1. Ankan

    “Overriding method can throw any unchecked exception(Runtime) but it can throw checked exception which is broader or new than those declared by the overriden method but it can throw fewer or narrow checked exception.”

    Did not get this point…

    Reply
    1. admin

      Hi Ankan,

      I got your message. Thanks for your kind words.
      As for as overloading and Overriding is concened, First you have to understand the concept of Exception.
      Exception can be divided two types.
      1- Checked
      2- Un-Checked

      Chcked exception is something which needs to be handled in code by developer while unchecked exception is not supposed to be handled in code, means developer is not forced to handle it in code.

      Now Broader exception.
      Exception has a particular hierarchy. When i say that broader means exception @ higher level in hierarchy.

      A is parent of B and B is parent of C.
      So if a method throws Exception of type C and overloaded/overriden method is throwing exception of type B then it is called broader exception throwing by overloaded or overriden method.

      For more details you can refer exception chapter.
      Hope it help you. Let me know in case you have more question.

      Thanks

      Reply
      1. Deepika

        Hello,

        Thanks for clarifying.

        I just wanted to summarize, what you have explained. Please correct m if I am wrong.

        If Parent class method is not throwing any exception,then child class overridden method can only throw unchecked(Run time) exception.(Not checked exception)

        If Parent class method is throwing any exception,then child class overridden method can only throw either same exception thrown by parent class method or no exception.But it should not throw any exception which is the child of exception thrown by parent class method.

        Thanks…

        Reply
        1. JBT

          Hi Deepika,

          Sorry for late reply. But your comment is confusing others. So here is the thing.
          All the understanding is correct except the last one. Where you said child class method should not throw an exception which is the child of the exception thrown by parent class method. But it is the opposite. The overriding method can throw child exception and not any higher exception. I have also added an exception for more clarity.
          In general, always remember in Java.
          PARENT CAN HANDLE CHILD BUT CHILD CAN NOT HANDLE PARENT.

          Reply
  2. Ravinder

    Hi Bro!,
    I am not getting properly what you explain so According to your written rules(about Override concept) If you provide with example then we are appreciate to you …

    Thanks
    Adv
    ravinder

    Reply
  3. Gajalakshmi

    Static methods can not be overridden. Static method looks to overridden but it is hidden.. where as in static block it has been specified that we could change the definition of the static block. I considered this as overriding the static method behavior.

    Could you please explain me.

    Reply

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.