Java 一个类中是否可以有多个名称相同但参数不同的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21058166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:15:51  来源:igfitidea点击:

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

javamethodsparameters

提问by user3184074

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

我以前用 C 编写过代码,但我对 Java 完全陌生我正在为我的 OOP 课程做一个教程,这几乎是我第一次正式学习这门语言

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).

在教程中,我的教授制作了一个课程,用于测试我必须自己制作的 I/O 助手类(顺便说一句,该教程是 (a) 可选和 (b) 不是为了分数,所以我通过制作这个线程不作弊或任何事情......和(c)我以前从未使用过Java,而我的许多其他同学都使用过,所以我落后了)。

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

反正。在他制作的测试类中,他调用了一个方法“getInt”,我需要将它放入我的 I/O 帮助器类中。

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

但是当他调用 getInt 方法时,他有时会使用 3 个参数,有时是 2 个,有时则没有,等等。

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?

我知道在 CI 中无法做到这一点(对吧?),但是在 Java 中可以做到吗?如果是这样,如何?

采纳答案by Elliott Frisch

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.

方法重载(或函数重载)在 C++ 和 Java 中是合法的,但前提是方法采用不同的参数(即做不同的事情)。你不能在C 中重载。

回答by Stephen C

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

是的,这是合法的。它被称为方法重载。它在 Oracle Java 教程 -此处进行了描述

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

以下是您如何使用重载getInt方法实现类。

    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.

通常(!)您需要在方法主体中放置不同的东西,以执行所需的操作。