Friday, July 24, 2009

Difference between Overriding and Overloading

Difference between Overriding and Overloading

Overriding is the example of run-time polymorphism and
Overloading is the example of compile-time polymorphism.

Overriding
■The return type must exactly match that of the overridden method.
■The access level must not be more restrictive than that of the overridden method.
■The access level can be less restrictive than that of the overridden method.
■The overriding method must not throw new or broader checked exceptions than those declared by the overridden method.
■The overriding method can throw narrower or fewer exceptions. Just because an overridden method “takes risks” doesn’t mean that the overriding subclass’ exception takes the same risks. Bottom line: An overriding method doesn’t have to declare any exceptions that it will never throw, regardless of what the overridden method declares.
■You cannot override a method marked final.
■If a method can’t be inherited, you cannot override it.
Overloaded method
■Overloaded methods must change the argument list.
■Overloaded methods can change the return type.
■Overloaded methods can change the access modifier.
■Overloaded methods can declare new or broader checked exceptions.
■A method can be overloaded in the same class or in a subclass.

5 comments:

  1. This is a great blog.....

    I wish I was doing .NET..i would have learnt so much....I can still learn a lot from it though....

    ReplyDelete
  2. Overloading

    deals with multiple methods in the same class with the same name but different signatures.
    class student
    {
    public string GetName(int id){...}
    public string GetName(string ssn){...}
    }
    Overriding
    deals with two methods, one in a parent class and one in a child class that have the same signature.
    Class ParentClass{
    public string GetName(int id, stringmatch){.}
    }
    Class ChildClass inherits ParentClass{
    public string GetName(stringmatch, int id){.}
    }

    ReplyDelete
  3. Hi

    I like this post:

    You create good material for community.

    Please keep posting.

    Let me introduce other material that may be good for net community.

    Source: Web interview questions

    Best rgs
    Peter

    ReplyDelete
  4. "access level can be less restrictive than that of the overridden method."

    The above statement is wrong because it won't compile when we try to change access specifier weather it is less restrictive.

    Check It.

    ReplyDelete
  5. When overriding, you change the method behavior for a derived class.
    e.g Clas A
    {
    Virtual void hi(int a)
    {
    }
    }

    Class B:A
    {
    public overrid void hi(int a)
    {

    }
    }

    Overloading simply involves having a method with the same name within the class.

    Example for Over loading

    Class A
    {
    class a()

    {

    }
    class a(int a)
    {
    }
    }

    ReplyDelete

 
Locations of visitors to this page