3 Replies Latest reply: Mar 26, 2013 7:02 AM by gimbal2 RSS

    Overloading and overriding question

    956015
      Hi,

      I have a question about overloading and overriding.

      Is the following considered overloading when the return types are different?
      public int function(int x);
      public string function(string x);
      Also if one of the above functions has a different access is that still considered overloading?

      Also do parameter names matter when overloading and overriding?
      For example can you override a function like this:
      In base class
      public int function(int x);
      In derived class
      public int function(int y);

      Thank you.
        • 1. Re: Overloading and overriding question
          rp0428
          Your questions can be answered by reviewing The Java Language Specification. See that entire section
          http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.9
          >
          8.4.9. Overloading
          If two methods of a class (whether both declared in the same class, or both inherited by a class, or one declared and one inherited) have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

          This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name, unless their signatures are override-equivalent.

          When a method is invoked (§15.12), the number of actual arguments (and any explicit type arguments) and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked (§15.12.2). If the method that is to be invoked is an instance method, the actual method to be invoked will be determined at run time, using dynamic method lookup (§15.12.4).
          . . .
          • 2. Re: Overloading and overriding question
            999199
            1) No, parameter names don't matter when overloading and overriding.

            But number of parameters and types of parameters matter in case of overloading.

            2)Yes, you can override a function like this:

            In base class
            public int function(int x);
            In derived class
            public int function(int y);

            Because signature of methods can be same in case of overriding.


            Cheers
            A Rahman
            • 3. Re: Overloading and overriding question
              gimbal2
              996196 wrote:
              1) No, parameter names don't matter when overloading and overriding.

              But number of parameters and types of parameters matter in case of overloading.
              Also the order of course. The basic deal is that the method signature has to match exactly. It is in one's interest to learn what a "method signature" exactly is.