user3184074
user3184074

Reputation: 71

Is it possible multiple methods with the same name but different parameters in a class?

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?

Upvotes: 1

Views: 65737

Answers (2)

Stephen C
Stephen C

Reputation: 718708

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.

Upvotes: 12

Elliott Frisch
Elliott Frisch

Reputation: 201409

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.

Upvotes: 13

Related Questions