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

后端 未结 2 954
悲&欢浪女
悲&欢浪女 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 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.

提交回复
热议问题