Java方法与函数

Java's methods vs. functions

本问题已经有最佳答案,请猛点这里访问。

我只是决定将我的MATLAB编程技巧与一些更为一致和严格的Java编码结合起来。所以我希望这不是一个太天真的问题。

我想知道是否有任何真正的原因,为什么Java引用的函数是EDOCX1,0,而不是EDCOX1,1?,正如许多其他程序语言所做的那样。

这是因为内部EDCOX1和Java 2的性质相比,如EDCOX1,3?还是有其他重要(或微妙)的原因?

事先谢谢。


一个方法和一个函数有点不同。

函数只是一个代码,您可以通过它的名称随时调用它,并且可以向它传递参数(也称为参数),还可以从任何函数(即函数的返回值)中获得结果。

但是一个方法是一个通过它的名字调用的代码,但是它与任何对象相关联。您也可以将参数传递给方法,还可以从方法中获得一些返回值,但问题是它们总是与一些对象相关联。

编辑

Java是面向对象的,在大多数情况下,不能让Java代码在没有类的情况下运行。然而,在C++中,可以不用类运行代码。所以在Java中,将有类和代码将在类中写入,因此它们被称为方法而不是函数,因为它们将与对象相关联。

但是在C++中,可以有一些函数,可以通过显式传递值来调用。

简单地说,方法是一个与对象相关的函数。


我认为这个数字http://www.jot.fm/issues/issue_2008_03/Article4/images/figure2.gif

one, two and three dimensional method dispatch

摘自http://www.jot.fm/issues/issue_2008_03/Article4/帮助理解OO和过程编程之间的主要区别之一。基本上是这样的

Procedural programming provides only one dimension to associate a
computational unit with a name. Here, procedure calls or names
are directly mapped to procedure implementations. In Figure a calling
m1 leaves no choice but the invocation of the only implementation of
procedure m1

虽然

Object-oriented programming adds another dimension for name resolution
to that of procedural programming . In addition to the method or
procedure name, message dispatch takes the message receiver into
consideration when looking up a method. In Figure 2b we see two
implementations of method m1. The selection of the appropriate method
not only depends on the the message name m1, but also the receiver of
the actual message, here Ry

图(c)的第三部分是面向主题的编程,其中对象的行为(称为方法)不仅取决于对象的状态,还取决于调用(或观察)对象的主题。然而,这实际上超出了您的问题范围。


在这部片子里,我忍不住想了很多不必要的戏剧。""方法"确实是一个名称,Java恰好用于子程序,这些子程序可能需要或不需要参数,并且可能返回或不返回值。

例如,有效的"方法"可能如下所示,而不涉及OO纯度、"函数"的规范定义等;以下两种方法也可以或不可以在执行过程中使用对象的当前"状态"(实例变量值):

1
2
3
4
5
// kind of a function, returns a value
public int calculateStuff(int param1)

// more of a procedure, presumably just"does stuff", returns nothing
public void doStuff(int param1)

它们是一样的。C++通常调用它们的函数。Java通常将它们称为方法。

方法通常与类关联。

您偶尔也会听到"类函数",这只是一个方法。

没关系,如果你给他们打电话,人们就会知道你在说什么。