Sunday, 20 August 2017

Overriding in Java

Method overriding

“same method name ,same parameters but in different class”

When same method name is presenting in both base class and derived class with same types of arguments or same order of arguments is known as method Overriding.

Method Overriding is used to give specific execution of a method that is already provided by its super class.

static method cannot be overridden.

Method Overriding is used for Runtime Polymorphism

we cannot over ride static method

method must have same name as in the base class.

method must have same parameter as in the base class.

must be IS-A relationship (inheritance).

 In overloading we have to make sure only methods names (must be same) and parameters types (must be different) apart from these the remaining like return type access modifiers etc. are not required to verify

But in overriding every things check like method names arguments types return types access modifiers etc.

Code
class parent
{
   int sum(int i)
   {
      return(i + 10);
   }
}
class child extends parent
{
   int sum(int f)
   {
                return(f+20);
   }
}

class Override
{
   public static void main(String args[])
   {
                child c = new child();
                int j = c.sum(7);
                System.out.println(j);
   }
}
Output:
27


In this post we learned about overriding in java.

0 comments:

Post a Comment