Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Method Overloading and Overriding In Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.08k
    Comment on it

    Method Overloading

    Method overloading can be achieved by declaring two methods with the same name and different signatures. These different signatures can be either

      1.Arguments with different data types, eg: method(int a, int b) vs method(String a, String b) or

      2.Variable number of arguments, eg: method(a) vs method(a, b)

    Method overloading cant be achieved with the first option because ruby doesnt have the feature of data type declaration or we can say dynamic typed language. So now the above method can be defined only as  def(a,b)

    Whereas if we look upon the second option we may feel that we can achieve method overloading through it but we cannot, the reason being if suppose we have two methods with different number of arguments.

    def method(a); 
    end;
    
    def method(a, b = true); 
    end;
    
    method(10)

    # second argument has a default value method(10)

    # Now the method call can match the first one as well as the second one,

    # so here is the problem. So the latter method will be called if we call 2
    methods with same name.

    Method Overriding 

    In object oriented programming, method overriding is a language feature in which a subclass can provide an implementation of a method which is already mentioned by its super classes.
    The implementation of a method in the subclass replaces the implementation of a method in the super class.

    Here's an example:

    class A
      def a
        puts 'In class A'
      end
    end
    
    class B < A
      def a
        puts 'In class B'
      end
    end
    
    b = B.new
    b.a

    The method a in class B overrides the method a in class A.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: