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

后端 未结 2 953
悲&欢浪女
悲&欢浪女 2021-01-29 10:23

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

I

相关标签:
2条回答
  • 2021-01-29 10:56

    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.

    0 讨论(0)
  • 2021-01-29 11:11

    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.

    0 讨论(0)
提交回复
热议问题