Method overriding in Java

Method overriding is re-writing the implementation of a existing method of a parent class in subclass.

It provides specific implementation of a method in subclass which is already defined in super class.

Example

class Book{

void numberofpages(){

System.out.println("Book covers 250 pages.");

}

}

class Chapter extends Book{

void numberofpages(){

System.out.println("This Chapter covers 30 pages.");

}

public static void main(String args[]){

Chapter firstchap= new Chapter();

firstchap.numberofpages();

}

}

Try In Editor

Output

This Chapter covers 30 pages.


Rules for overriding a method

  • Method name of subclass should be same as in superclass.
  • Number of parameters of the overridden method in subclass should be same as its method in superclass
  • datatype of the parameters of the overridden method in subclass should be same as its method in superclass.
  • This is applicable only when it follows parent-child relationship i.e inherited