Which class is super class of every class

What restrictions placed method overriding

Answer : In parent child class hierarchy if a method in a child class has the same name and type signature as a method in its superclass, then the method in the child class is said to override the method in the superclass. If overrridden method is called from within the child class it will refer to the version of that method defined in the child class. The version of the method defined by the superclass will be hidden.

Following below restriction placed on method overriding:

  • Overridden methods must have the  return type, argument list, and same name
  • The overriding method may not limit the access of the method it overrides
  • The overriding method may not throw any exceptions that may not be thrown by the overridden method  otherwise you will see compile time exception ( Exception is not compatible with throws clause in overriding method name )

Please have example below:

package com.javahonk.overriding;

public class OverridingTest extends TopClass {

    public static void main(String[] args) throws Exception {
	OverridingTest overridingTest=new OverridingTest();
	overridingTest.calculateNumber(3, 6);
    }

    void calculateNumber(int a, int b) throws Exception {
	int c = a * b;
	System.out.println("Child class Result a*b:  "+c);

    }

}

class TopClass {

    void calculateNumber(int a, int b) throws Exception {
	int c = a * b;
	System.out.println("Top class Result a*b"+c);

    }

}

 

Output:

What restrictions placed method overriding

Leave a Reply

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