1

I've coded in C before, but I'm completely new to java I'm doing a tutorial for my OOP class, and this is pretty much my first time officially learning the language

In the tutorial, my professor made a class that will be used to test an I/O helper class that I have to make myself (and btw, the tutorial is (a) optional and (b) not for marks, so I'm not cheating or anything by making this thread... and (c) I've never used java before whereas a lot of my other classmates have, so I'm behind).

ANYWAY. In his testing class that he made, he calls a method "getInt" that I need to put into my I/O helper class.

However when he calls the getInt method, he sometimes uses 3 parameters, sometimes 2, sometimes none, etc.

I know in C I wouldn't be able to do that (right?), but is it possible to do in Java? And if so, how?

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user3184074
  • 71
  • 1
  • 2
  • 6
  • 2
    See [Overloaded Methods](http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html): "The Java programming language supports overloading methods, and *Java can distinguish between methods with different method signatures [but the same name]*. This means that methods within a class can have the same name if they have different parameter lists.." (Java is not C.) – user2864740 Jan 11 '14 at 03:24
  • 1
    Also, note that overloading is *not related* to "OOP" - not all OOP languages support overloading, and some languages with overloading are not OOP. – user2864740 Jan 11 '14 at 03:26

2 Answers2

13

Method overloading (or Function overloading) is legal in C++ and in Java, but only if the methods take a different arguments (i.e. do different things). You can't overload in C.

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
12

Yes it is legal. It is called method overloading. It is decribed in the Oracle Java Tutorial - here.

Here's how you might implement a class with an overloaded getInt method.

    public class Foo {
        ...
        public int getInt(String s1) {
            // get and return an int based on a single string.
        }

        public int getInt(String s1, int dflt) {
            // get and return an int based on a string and an integer
        }
    }

Typically (!) you need to put different stuff in the method bodies, to do what is required.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • thanks for the fast reply!! My problem is that I have my helper class that's pretty much done, but it only works for when the prof has included all 3 parameters. For all of the other instances there are those red Eclipse X's and it's telling me that my parameters don't match. How do I go about fixing the problem? – user3184074 Jan 11 '14 at 03:26
  • 3
    It is not clear what you are asking, but it *sounds* like *you* need to implement all of the overloads of the `getInt` method in your class ... that his helper class is calling. – Stephen C Jan 11 '14 at 03:28