top of page
kinjalben rana

METHOD OVERRIDING IN JAVA

 

If subclass (child class) has the same method name and parameters as declared in the superclass (parent class), it is known as Method Overriding. Method overriding is used to provide the specific implementation of a method that has been declared by its parent class. Method overriding is used for runtime polymorphism.


Rules for Method Overriding:

·       The method must have the same name as in the parent class.

·       The method must have the same parameter as in the parent class.

·       There must be an IS-A relationship (inheritance).


Example of Method Overriding:

In this example, we have defined the color method. The color method in subclass has specific implementation of a method that has been defined in the superclass. There is IS-A relationship between the parent class and sub class, the name and parameter of the method are the same, so it is method overriding.

 

class Flower{  

{     void color()

      {           System.out.println (“Colorful flowers”);           }

 } 

 

class Rose extends Flower

{     void color()

      {           System.out.println (“Rose is red”);  }


public static void main(String[] args)

{        Rose r1 = new Rose();

            r1.run();        

}

 }  

 

OUTPUT:             Rose is red

8 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page