Showing posts with label overriding. Show all posts
Showing posts with label overriding. Show all posts

Wednesday, 6 January 2016

Method Overriding in Java

                                    

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

That means if subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.


Usage of Java Method Overriding

  • Method overriding is used to provide specific usage of a method that is already provided by its super class (parent class).
  • Method overriding is used for runtime polymorphism

Eg:

One of the simplest example - Here A class extends B class. Both the classes have a common method void run(). B class is giving its own implementation to the run() method or in other words it is overriding the method run().


class B{
   public void run()
   {
      System.out.println("Inside B");
   }
}
class A extends B{
   public void run(){
      System.out.println("Inside A");
   }
   public static void main( String args[]) {
      A obj = new A();
      obj.run();
   }
}
Output:
Inside A
Advantage of method overriding: The main advantage of method overriding is that the class can give its own specific implementation to a inherited method without even modifying the parent class(base class).

Tuesday, 21 January 2014

Using final with Inheritance

how to use final apply to inheritance.

Using final to Prevent Overriding


While method overriding is one of Java’s most powerful features.To disallow a method from being overridden,specify final as a modifier at the start of its declaration.

METHOD OVERRIDING IN JAVA

Method Overriding

Brief note about method overriding 


Method overriding means have same signature but with different implementation. It occurs when a class declares a method that has the same type signature as a method declared by one of its super classes.Signature is a combination of a method name and the sequence of its parameter types.When a method in the subclass overrides a method in a super class, the method in the super class is hidden relative to the subclass object.Method Overriding is a very important feature of java because it forms the basis for run-time polymorphism.