❮ Previous Next ❯

Java Method Overriding:

When a method name and its signature in both the super and sub class is same, then the method in the sub class is said to be an overridden method.

When the overridden method is called from within a sub class , it always refer to the version of that method defined by the sub class. That means the method defined by the super class will be hidden.

Let us see a program to understand method overriding.

Example

MethodOverriddingDemo.java

package java8s;

class Vehicle
{
      void move()
      {
            System.out.println("vehicle is running");
      }
}

class Car extends Vehicle
{
      void move()
      {
            System.out.println("car is running");
      }
}
public class MethodOverriddingDemo {

      public static void main(String[] args) {
            Car c=new Car();
            c.move();

      }

}


Output

method overriding

As you can see here Test1 class gives it own implementation of show() method. Method must have same name and same type signature.

NOTE :

Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

Difference between method Overloading and Method Overriding in java:

It is one of the common interview questions for freshers.There are three basic differences between the method overloading and method overriding.

Method Overloading Method Overriding
The name of the method must be same and the signature must be different. Both name and signature must be same.
Compile time polymorphism. Runtime polymorphism.
Used to readability of code. Used to reusability of code.

Can we override static method ? Explain with reasons:

No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.

❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved